class property(fget=None, fset=None, fdel=None, doc=None)
返回一个property属性
fget:获取属性值
fset:设置属性值
fdel:删除属性
doc:属性描述
注意,如果设置了doc参数,则参数值就是属性的docstring,否则系统将会读取fget参数的docstring(如果存在)作为属性的docstring,下面会示例说明(参见图一)
property典型用法是定义托管属性
class C:
def __init__(self):
self._x = None
def get_x(self):
"""I'm get_x method"""
print('get_x invoked')
return self._x
def set_x(self, value):
print('set_x invoked')
self._x = value
def del_x(self):
print('del_x invoked')
del self._x
# 设置doc参数
x = property(get_x, set_x, del_x, "I'm the 'x' property.")
# 不设置doc参数
x0 = property(get_x, set_x, del_x)
验证代码
if __name__ == '__main__':
c = C()
print(help(c))
c.x = '100'
c.x
del c.x
执行结果:
从上面的代码执行结果中,我们可以看到:对于类property,如果设置了doc参数,则参数值就是属性的docstring,否则系统将会读取fget参数的docstring(如果存在)作为属性的docstring,因此,我们可以使用@property装饰器来创建只读属性,@property装饰器会将方法转换为相同名称的只读属性。
class Parrot:
def __init__(self):
self._voltage = 100000
@property
def voltage(self):
"""Get the current voltage."""
return self._voltage
一个property对象包含三个方法:getter, setter, deleter,当一个函数被@property装饰器修饰时,系统会自动创建一个包含对应访问函数的同名属性,我们示例说明:
class C:
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
上述示例与本章第一个例子定义一样