【发布时间】:2014-08-22 01:29:05
【问题描述】:
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
它打印“get() 被调用”,实例,所有者并返回自我<__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> 处没有 main.C 对象?
【问题讨论】:
标签: python-3.x descriptor