|

楼主 |
发表于 2021-7-20 17:07:56
|
显示全部楼层
- class A:
- x = 666
- def __get__(self, instance, owner):
- print (self,'self')
- print (instance,'instance')
- print (owner,'owner')
- print('get~')
- return self
- def __getattribute__(self, item):
- print('getattribute')
- class B:
- a = A()
- a = A()
- b = B()
- #a.x
- #print (a,'a')
- #print (b,'b')# 通过实例访问属性,都会经过__getattribute__函数。而当该属性不存在时,仍会先访问__getattribute__,但是之后还会接着要访问__getattr__ ,弹出异常。
- print (b.a.x ) # 每次访问描述符(descriptor)(即定义了__get__的类),都会先经过__get__函数。
- #类方法中定义了__get__就是描述符,从一个类实例访问另一个实例或者它的属性,都会首先触发__get__
复制代码
我把代码改成这种,结果是:<__main__.A object at 0x000001F6D5753C48> self
<__main__.B object at 0x000001F6D5753D08> instance
<class '__main__.B'> owner
get~
getattribute
None
不知道为啥getattribute被触发了,然后打印了个None?? |
|