我已经成功地使用了 Python 属性,但我不知道它们是如何工作的。如果我取消引用类之外的属性,我只会得到一个 property
类型的对象:
@property
def hello(): return "Hello, world!"
hello # <property object at 0x9870a8>
但是如果我把一个属性放在一个类中,行为就大不相同了:
class Foo(object):
@property
def hello(self): return "Hello, world!"
Foo().hello # 'Hello, world!'
我注意到未绑定(bind)的 Foo.hello
仍然是 property
对象,所以类实例化一定是在施展魔法,但那是什么魔法呢?
最佳答案
正如其他人所指出的,他们使用一种称为描述符的语言功能。
通过Foo.hello
类访问时返回实际属性对象的原因在于属性如何实现__get__(self, instance, owner)
特殊方法:
- 如果在 instance 上访问描述符,则将该实例作为适当的参数传递,并且
owner
是该实例的 class实例。 - 通过类访问时,则
instance
为None,只传递owner
。property
对象识别并返回self
。
除了Descriptors howto ,另见 Implementing Descriptors 上的文档和 Invoking Descriptors在语言指南中。
关于python - Python 属性如何工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6193556/