class C(object):
a = 'abc'
def __getattribute__(self, *args, **kwargs):
print("__getattribute__() is called")
return object.__getattribute__(self, *args, **kwargs)
def __getattr__(self, name):
print("__getattr__() is called ")
return name + " from getattr"
def __get__(self, instance, owner):
print("__get__() is called", instance, owner)
return self
def foo(self, x):
print(x)
class C2(object):
d = C()
>>>c2=C2()
>>>c2.d
__get__() is called <__main__.C2 object at 0x000000000297BE10> <class '__main__.C2'>
<__main__.C object at 0x000000000297BBA8>
我理解结果,c2.d触发C类中的 get 方法。
def __get__(self, instance, owner):
print("__get__() is called", instance, owner)
return self
打印“获取()被称为”,实例,所有者并返回自我<__main__.C object at 0x000000000297BBA8>
>>> c2.d.a
__get__() is called <__main__.C2 object at 0x000000000297BE10> <class '__main__.C2'>
__getattribute__() is called
'abc'
为什么c2.d.a的结果不是:
__get__() is called <__main__.C2 object at 0x000000000297BE10> <class __main__.C2'>
<__main__.C object at 0x000000000297BBA8>
__getattribute__() is called
'abc'
为什么C类 get 方法中的return self
不起作用?为什么在0x000000000297BBA8&gt;处没有&lt; main .C对象在输出?
答案 0 :(得分:0)
&lt; main .C对象位于0x000000000297BBA8&gt;
不是打印的一部分,它是c2.d表达式的结果。