python 3.3 文档告诉我应该可以直接访问属性描述符,尽管我对它的语法持怀疑态度x.__get__(a)
。但是我在下面构建的示例失败了。我错过了什么吗?
class MyDescriptor(object):
"""Descriptor"""
def __get__(self, instance, owner):
print "hello"
return 42
class Owner(object):
x = MyDescriptor()
def do_direct_access(self):
self.x.__get__(self)
if __name__ == '__main__':
my_instance = Owner()
print my_instance.x
my_instance.do_direct_access()
这是我在 Python 2.7(以及移植代码片段后的 Python 3.2)中遇到的错误。该错误消息对我来说很有意义,但这似乎不是文档所说的那样。
Traceback (most recent call last):
File "descriptor_test.py", line 15, in <module>
my_instance.do_direct_access()
File "descriptor_test.py", line 10, in do_direct_access
self.x.__get__(self)
AttributeError: 'int' object has no attribute '__get__'
shell returned 1