class A:
x = 1
def __getattr__(self,name):
print("__getattr__ of A")
def __getattribute__(self,name):
print("__getattribute__ of A")
return super().__getattribute__(name)
class B(A):
x = 2
def __getattr__(self,name):
print("__getattr__ of B")
def __getattribute__(self,name):
print("__getattribute__ of B")
a = A()
return a.__getattribute__(name)
b = B()
print(b.x)
I want to ask Why A will be printed twice.I have tried debug ,but after that I am more puzzled.Thanks.
the __getattribute__
method is called twice on line 16: first implicitly to get the __getattribute__
method itself, and then explicitly by your code.
(Jul-25-2018, 11:19 AM)stranac Wrote: [ -> ]the __getattribute__
method is called twice on line 16: first implicitly to get the __getattribute__
method itself, and then explicitly by your code.
Thank you.But I have an another problem,
class B(A):
x = 2
def __getattr__(self,name):
print("__getattr__ of B")
def __getattribute__(self,name):
print("__getattribute__ of B")
return object().__getattribute__(name)
b = B()
b.x
why the output is:
__getattribute__ of B
__getattr__ of B
In this case,
__getattribute__
gets called first, and raises an
AttributeError
, because
x
is an attribute of the class, not the instance.
When this happens,
__getattr__
gets called to get the class attribute.
You should read
https://docs.python.org/3/reference/datamodel.html to get a better understanding of how all of this stuff works.