Note that there are some explanatory texts on larger screens.

plurals
  1. PODescriptors as instance attributes in python
    primarykey
    data
    text
    <p>To the question:</p> <blockquote> <p>Why can't descriptors be instance attributes?</p> </blockquote> <p>it has been <a href="https://stackoverflow.com/questions/2954331/dynamically-adding-property-in-python">answered</a> that:</p> <blockquote> <p>descriptor objects needs to live in the class, not in the instance</p> </blockquote> <p>because that is the way that the <code>__getattribute__</code> is implemented.</p> <p>A simple example. Consider a descriptor:</p> <pre><code>class Prop(object): def __get__(self, obj, objtype=None): if obj is None: return self return obj._value * obj._multiplier def __set__(self, obj, value): if obj is None: return self obj._value = value class Obj(object): val = Prop() def __init__(self): self._value = 1 self._multiplier = 0 </code></pre> <p>Consider the case in which each obj has multiple Prop: I would need to use unique names to identify the values and multipliers (Like <a href="https://stackoverflow.com/questions/2954331/dynamically-adding-property-in-python">here</a>. Having a per instance descriptor object would allow to store the <code>_multiplier</code> (and the <code>_value</code>) in the descriptor itself, simplifying a few things.</p> <p>To implement per instance descriptor attributes you need to either:</p> <ol> <li>create a per instance class <a href="https://stackoverflow.com/questions/2954331/dynamically-adding-property-in-python">See here</a></li> <li>override <code>__getattribute__</code> <a href="https://stackoverflow.com/questions/10232174/can-a-python-descriptor-be-used-to-instantiate-an-attribute-in-the-init-of-a">See here</a></li> </ol> <p>I am aware that similar questions have been raised before, but I have not found a real explanation:</p> <ol> <li>Why Python is designed this way?</li> <li>What is the suggested way to store information that the descriptor needs but is per instance?</li> </ol>
    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.
 

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