[Tutor] How to set variables inside a class()
eryksun
eryksun at gmail.com
Tue Nov 26 19:40:49 CET 2013
On Tue, Nov 26, 2013 at 6:13 AM, Dominik George <nik at naturalnet.de> wrote:
> Now when zou instantiate the class, then the dictionary is copied to the
> instance (carying references to the same data inside it, mind you!),
Perhaps the above is just a simple mistake of wording, but to be
clear, the class dict isn't copied to an instance.
>>> class Animal(object): # extend object!!!
... flag = True
...
>>> a = Animal()
>>> Animal.__dict__['flag']
True
>>> a.__dict__ # or vars(a)
{}
The generic object __getattribute__ (tp_getattro slot in the C
implementation) looks in the dicts of the type and its bases, i.e. the
types in the MRO:
>>> class Dog(Animal):
... flag = False
...
>>> Dog.__mro__
(<class '__main__.Dog'>, <class '__main__.Animal'>,
<type 'object'>)
The order of possible return values is as follows:
* a data-descriptor class attribute (e.g. a property):
return the result of its __get__ method
* an instance attribute
* a non-data descriptor class attribute (e.g. a function):
return the result of its __get__ method
(e.g. return a bound instance method)
* a non-descriptor class attribute
If the attribute isn't found it raises an AttributeError. If you
implement the fallback __getattr__ method, the AttributeError is
swallowed and the onus is on you.
More information about the Tutor
mailing list