|
30鱼币
题目如图,我也调试过了,调试中发生的事情是这样的B达到return a.__getattribute__(name)后去到了A的__getattribute__(self,name),这时A的那句会被打印第一次,然后A的__getattribute__(self,name)执行完后又到B的__getattribute__(self,name),然后B又跳到A,这时A的那句会被打印第二次,这次A执行完后程序就结束了,想不通第一次A为什么会跳回B。
用如下代码证明第一个应该是由super().__getattribute__(name)调用的
- class A:
- x = 1
- def __getattr__(self,name):
- print("A的__getattr__")
- def __getattribute__(self,name,isB = False):
- if(isB):
- print("B调用")
- else:
- print("非B调用")
- print("A的__getattribute__")
- return super().__getattribute__(name)
- class B(A):
- x = 2
- def __getattr__(self,name):
- print("B的__getattr__")
- def __getattribute__(self,name):
- print("B的__getattribute__")
- a = A()
- return a.__getattribute__(name,True)
- b = B()
- print(b.x)
复制代码
结果:
B的__getattribute__
非B调用
A的__getattribute__
B调用
A的__getattribute__
1
|
最佳答案
查看完整内容
用如下代码证明第一个应该是由super().__getattribute__(name)调用的
结果:
B的__getattribute__
非B调用
A的__getattribute__
B调用
A的__getattribute__
1
|