小白教程
所有教程
关于
Search
172.69.6.29
172.69.6.29
参数设置
贡献
退出
操作
编辑
移动
保护
信息
历史
删除
查看“Python func property”的源代码
本页内容
上一节:
Python3_string_len
下一节:
Python_func_type
因为以下原因,您没有权限编辑本页:
您请求的操作仅限属于该用户组的用户执行:
用户
您可以查看和复制此页面的源代码。
{{DISPLAYTITLE:property()}}[[Category:python3 built in functions|43]] = Python property() 函数 = [[python built in functions|Python 内置函数]] == 描述 == '''property()''' 函数的作用是在新式类中返回属性值。 === 语法 === 以下是 property() 方法的语法: <sample title="" desc="" lang="python" hererun="1"> class property([fget[, fset[, fdel[, doc]]]]) </sample> === 参数 === * fget -- 获取属性值的函数 * fset -- 设置属性值的函数 * fdel -- 删除属性值函数 * doc -- 属性描述信息 === 返回值 === 返回新式类属性。 == == 定义一个可控属性值 x == <sample title="" desc="" lang="python" hererun="1"> 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.") </sample> 如果 c 是 C 的实例化, c.x 将触发 getter,c.x = value 将触发 setter , del c.x 触发 deleter。 如果给定 doc 参数,其将成为这个属性值的 docstring,否则 property 函数就会复制 fget 函数的 docstring(如果有的话)。 将 property 函数用作装饰器可以很方便的创建只读属性: <sample title="" desc="" lang="python" hererun="1"> class Parrot(object): def __init__(self): self._voltage = 100000 @property def voltage(self): """Get the current voltage.""" return self._voltage </sample> 上面的代码将 voltage() 方法转化成同名只读属性的 getter 方法。 property 的 getter,setter 和 deleter 方法同样可以用作装饰器: <sample title="" desc="" lang="python" hererun="1"> 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 </sample> 这个代码和第一个例子完全相同,但要注意这些额外函数的名字和 property 下的一样,例如这里的 x。 [[python built in functions|Python 内置函数]]
返回至“
Python func property
”。
上一节:
Python3_string_len
下一节:
Python_func_type