该函数返回一个特殊的描述符对象:property()
>>> property()
<property object at 0x10ff07940>
正是这个对象具有额外的方法:
>>> property().getter
<built-in method getter of property object at 0x10ff07998>
>>> property().setter
<built-in method setter of property object at 0x10ff07940>
>>> property().deleter
<built-in method deleter of property object at 0x10ff07998>
这些也充当装饰器。它们返回一个新的属性对象:
>>> property().getter(None)
<property object at 0x10ff079f0>
这是旧对象的副本,但替换了其中一个函数。
请记住,语法只是语法糖;语法:@decorator
@property
def foo(self): return self._foo
真的意味着同样的事情
def foo(self): return self._foo
foo = property(foo)
所以函数被替换为 ,我们上面看到的是一个特殊的对象。然后,当您使用 时,您正在做的是调用我上面向您展示的方法,该方法返回该属性的新副本,但这次使用setter函数替换为修饰的方法。foo
property(foo)
@foo.setter()
property().setter
下面的序列还使用这些装饰器方法创建一个 full on 属性。
首先,我们创建一些函数和一个只有一个 getter 的对象:property
>>> def getter(self): print('Get!')
...
>>> def setter(self, value): print('Set to {!r}!'.format(value))
...
>>> def deleter(self): print('Delete!')
...
>>> prop = property(getter)
>>> prop.fget is getter
True
>>> prop.fset is None
True
>>> prop.fdel is None
True
接下来,我们使用该方法添加一个 setter:.setter()
>>> prop = prop.setter(setter)
>>> prop.fget is getter
True
>>> prop.fset is setter
True
>>> prop.fdel is None
True
最后,我们使用以下方法添加一个删除器:.deleter()
>>> prop = prop.deleter(deleter)
>>> prop.fget is getter
True
>>> prop.fset is setter
True
>>> prop.fdel is deleter
True
最后但并非最不重要的一点是,该对象充当描述符对象,因此它具有.__get__()
,.__set__()
和.__delete__()
方法,以挂接到实例属性中获取,设置和删除:property
>>> class Foo: pass
...
>>> prop.__get__(Foo(), Foo)
Get!
>>> prop.__set__(Foo(), 'bar')
Set to 'bar'!
>>> prop.__delete__(Foo())
Delete!
描述符 Howto 包含该类型的纯 Python 示例实现:property()
class Property:
"Emulate PyProperty_Type() in Objects/descrobject.c"
def __init__(self, fget=None, fset=None, fdel=None, doc=None):
self.fget = fget
self.fset = fset
self.fdel = fdel
if doc is None and fget is not None:
doc = fget.__doc__
self.__doc__ = doc
def __get__(self, obj, objtype=None):
if obj is None:
return self
if self.fget is None:
raise AttributeError("unreadable attribute")
return self.fget(obj)
def __set__(self, obj, value):
if self.fset is None:
raise AttributeError("can't set attribute")
self.fset(obj, value)
def __delete__(self, obj):
if self.fdel is None:
raise AttributeError("can't delete attribute")
self.fdel(obj)
def getter(self, fget):
return type(self)(fget, self.fset, self.fdel, self.__doc__)
def setter(self, fset):
return type(self)(self.fget, fset, self.fdel, self.__doc__)
def deleter(self, fdel):
return type(self)(self.fget, self.fset, fdel, self.__doc__)