Python属性如何工作?

我已经成功使用了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!'

我注意到未绑定Foo.hello仍然是property对象,因此类实例化必须在做魔术,但这是什么魔术?


慕姐4208626
浏览 336回答 3
3回答

拉莫斯之舞

正如其他人指出的那样,它们使用称为描述符的语言功能。当您通过类访问实际属性对象时,返回该属性对象的原因在于该属性Foo.hello如何实现__get__(self, instance, owner)特殊方法:如果在实例上访问了描述符,则该实例作为适当的参数传递,并且owner是该实例的类。当通过类访问它时,instance则为None且仅owner通过。该property对象认识到这一点并返回self。除了“ 描述符”方法外,另请参阅《语言指南》中有关实现描述符和调用描述符的文档。

交互式爱情

为了使@properties正常工作,该类必须是object的子类。当该类不是对象的子类时,则首次尝试访问setter时,它实际上会创建一个名称较短的新属性,而不是通过setter进行访问。以下无法正常工作。class C(): # <-- Notice that object is missing&nbsp; &nbsp; def __init__(self):&nbsp; &nbsp; &nbsp; &nbsp; self._x = None&nbsp; &nbsp; @property&nbsp; &nbsp; def x(self):&nbsp; &nbsp; &nbsp; &nbsp; print 'getting value of x'&nbsp; &nbsp; &nbsp; &nbsp; return self._x&nbsp; &nbsp; @x.setter&nbsp; &nbsp; def x(self, x):&nbsp; &nbsp; &nbsp; &nbsp; print 'setting value of x'&nbsp; &nbsp; &nbsp; &nbsp; self._x = x>>> c = C()>>> c.x = 1>>> print c.x, c._x1 0以下将正常工作class C(object):&nbsp; &nbsp; def __init__(self):&nbsp; &nbsp; &nbsp; &nbsp; self._x = None&nbsp; &nbsp; @property&nbsp; &nbsp; def x(self):&nbsp; &nbsp; &nbsp; &nbsp; print 'getting value of x'&nbsp; &nbsp; &nbsp; &nbsp; return self._x&nbsp; &nbsp; @x.setter&nbsp; &nbsp; def x(self, x):&nbsp; &nbsp; &nbsp; &nbsp; print 'setting value of x'&nbsp; &nbsp; &nbsp; &nbsp; self._x = x>>> c = C()>>> c.x = 1setting value of x>>> print c.x, c._xgetting value of x1 1
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python