Ishak Hamed
Ishak Hamed

Reputation: 31

Derived class attributes

Class A(): 
    x=0 

class B(A): 
    b=1

1-print(B.__dict__) # no x attribute in B.dict

if B.x==0:
    B.x=1

2-print(B.__dict__) # there is x attribute in B.dict Why the output is different in 1 and 2?

Upvotes: 1

Views: 62

Answers (1)

juanpa.arrivillaga
juanpa.arrivillaga

Reputation: 96360

Because x belongs to A. Note, B has access to the A namespace, since it inherits from A, but that doesn't mean that the two namespaces are equivalent. B has an x attribute in your second example because you gave an x attribute to B: i.e. B.x=1

It is important to familiarize yourself with the Python Data Model. Note, in the standard type hierachy under "custom classes" there is some highly relevant information:

Custom class types are typically created by class definitions (see section Class definitions). 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 to C.__dict__["x"] (although 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. This search of the base classes uses the C3 method resolution order which behaves correctly even in the presence of ‘diamond’ inheritance structures where there are multiple inheritance paths leading back to a common ancestor. Additional details on the C3 MRO used by Python can be found in the documentation accompanying the 2.3 release at https://www.python.org/download/releases/2.3/mro/.

...

Class attribute assignments update the class’s dictionary, never the dictionary of a base class.

Upvotes: 1

Related Questions