我想了解内置函数property
是如何工作的。令我困惑的是property
也可以用作装饰器,但它只在用作内置函数时接受参数,而在用作装饰器时不接受参数。
这个例子来自documentation:
class C(object):
def __init__(self):
self._x = None
def getx(self):
return self._x
def setx(self, value):
self._x = value
def delx(self):
del self._x
x = property(getx, setx, delx, "I'm the 'x' property.")
property
的参数是getx
、setx
、delx
和一个doc字符串。
在下面的代码中,property
用作decorator。它的对象是x
函数,但是在上面的代码中,在参数中没有对象函数的位置。
class C(object):
def __init__(self):
self._x = None
@property
def x(self):
"""I'm the 'x' property."""
return self._x
@x.setter
def x(self, value):
self._x = value
@x.deleter
def x(self):
del self._x
如何创建x.setter
和x.deleter
装饰器?
我很困惑。
property()
函数返回一个特殊的descriptor object:这个对象有额外的方法:
它们也扮演装饰者的角色。它们返回一个新的属性对象:
这是旧对象的副本,但替换了其中一个函数。
记住,
@decorator
语法只是语法糖;语法:真的和
因此
foo
函数被property(foo)
替换,上面我们看到的是一个特殊的对象。然后,当您使用@foo.setter()
时,您所做的是调用我在上面向您展示的property().setter
方法,它将返回属性的新副本,但这次将setter函数替换为修饰方法。下面的序列还使用那些decorator方法创建一个full-on属性。
首先,我们使用getter创建一些函数和一个
property
对象:接下来,我们使用
.setter()
方法添加setter:最后,我们使用
.deleter()
方法添加一个deleter:最后但并非最不重要的是,} 、^{} 和^{} 方法来钩住实例属性获取、设置和删除:
property
对象充当descriptor object,因此它有^{描述符Howto包含一个
property()
类型的pure Python sample implementation:下面是一个如何实现
@property
的最小示例:否则
word
将保持方法而不是属性。Documentation says这只是创建只读属性的快捷方式。所以
相当于
相关问题 更多 >
编程相关推荐