Baloo
Baloo

Reputation: 11

why python __dict__ doesnot inherit class attribute but can access it

class A(object):
    name = "Class A"

class B(A):
    pass
print A.__dict__
print B.__dict__

output:

{'__dict__': <attribute '__dict__' of 'A' objects>, '__module__': '__main__', '_
_weakref__': <attribute '__weakref__' of 'A' objects>, 'name': 'Class A', '__doc
__': None}


{'__module__': '__main__', '__doc__': None}

The attr 'name' was not in B.dict, but can access by 'B.name'.

print B.name

output:

B.name =  Class A

I am still confused what's the difference between getattr function and Class.__dict__.

Upvotes: 0

Views: 44

Answers (1)

BrenBarn
BrenBarn

Reputation: 251363

B.__dict__ is only the things defined directly on B. When you try to access an attribute, a dynamic lookup process takes place, whereby the superclasses are tried in order to see which (if any) has the attribute.

Upvotes: 3

Related Questions