Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>There is only one descriptor object, stored on the class object, so <code>self</code> is always the same. If you want to store data per-object and access it through the descriptor, you either have to store the data on each object (probably the better idea) or in some data-structure keyed by each object (an idea I don't like as much).</p> <p>I would save data on the instance object: </p> <pre><code>class Desc(object): default_value = 10 def __init__(self, name): self.name = name def __get__(self,obj,objtype): return obj.__dict__.get(self.name, self.default_value) # alternatively the following; but won't work with shadowing: #return getattr(obj, self.name, self.default_value) def __set__(self,obj,val): obj.__dict__[self.name] = val # alternatively the following; but won't work with shadowing: #setattr(obj, self.name, val) def __delete__(self,obj): pass class MyClass(object): desc = Desc('varx') </code></pre> <p>In this case, the data will be stored in the <code>obj</code>'s 'varx' entry in its <code>__dict__</code>. Because of how data descriptor lookup works though, you can "shadow" the storage location with the descriptor:</p> <pre><code>class MyClass(object): varx = Desc('varx') </code></pre> <p>In this case, when you do the lookup:</p> <pre><code>MyClass().varx </code></pre> <p>The descriptor object gets called and can do its lookup, but when the lookup goes like this:</p> <pre><code>MyClass().__dict__['varx'] </code></pre> <p>The value is returned directly. Thus the descriptor is able to store its data in a 'hidden' place, so to speak.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload