Python Class Inheritance And __dict__ Lookup
Solution 1:
@bgporter has given a good explanation of the behaviour, I'll just go into why a little:
If your class variable was in B.__dict__
, how would it function? Each subclass would have its own value for a
, independent of the value for A.a
- this is not what you would expect. A class variable should exist once - in that class.
Instead, Python does a lookup on the class and if it doesn't exist, then looks up to its base classes - note that means it is possible to shadow a class variable in a subclass.
Solution 2:
That's how Python's object model works:
A class has a namespace implemented by a dictionary object. Class attribute references are translated to lookups in this dictionary, e.g.,
C.x
is translated toC.__dict__["x"]
(although for new-style classes in particular there are a number of hooks which allow for other means of locating attributes). When the attribute name is not found there, the attribute search continues in the base classes.
Post a Comment for "Python Class Inheritance And __dict__ Lookup"