Python 属性如何工作? [英] How do Python properties work?

查看:36
本文介绍了Python 属性如何工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经成功地使用了 Python 属性,但我不知道它们是如何工作的.如果我在类之外取消引用一个属性,我只会得到一个 property 类型的对象:

I've been successfully using Python properties, but I don't see how they could work. If I dereference a property outside of a class, I just get an object of type property:

@property
def hello(): return "Hello, world!"

hello  # <property object at 0x9870a8>

但是如果我把一个属性放在一个类中,行为就会大不相同:

But if I put a property in a class, the behavior is very different:

class Foo(object):
   @property
   def hello(self): return "Hello, world!"

Foo().hello # 'Hello, world!'

我注意到未绑定的 Foo.hello 仍然是 property 对象,所以类实例化一定是在施展魔法,但那是什么魔法?

I've noticed that unbound Foo.hello is still the property object, so class instantiation must be doing the magic, but what magic is that?

推荐答案

正如其他人所指出的,他们使用一种称为描述符的语言功能.

As others have noted, they use a language feature called descriptors.

通过类Foo.hello访问时返回实际属性对象的原因在于该属性如何实现__get__(self, instance, owner) 特殊方法:

The reason that the actual property object is returned when you access it via a class Foo.hello lies in how the property implements the __get__(self, instance, owner) special method:

  • 如果在实例上访问描述符,则该实例作为适当的参数传递,并且owner是该实例的实例.
  • 通过类访问时,instance为None,只传递owner.property 对象识别出这一点并返回 self.
  • If a descriptor is accessed on an instance, then that instance is passed as the appropriate argument, and owner is the class of that instance.
  • When it is accessed through the class, then instance is None and only owner is passed. The property object recognizes this and returns self.

除了 Descriptors howto,另请参阅关于 实现描述符语言指南中的调用描述符.

Besides the Descriptors howto, see also the documentation on Implementing Descriptors and Invoking Descriptors in the Language Guide.

这篇关于Python 属性如何工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆