GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing www.runoob.com — Python property() 函数 | 菜鸟教程
Python 基础教程
Python 基础教程
Python 简介
Python 环境搭建
Python 中文编码
Python VS Code
Python 基础语法
Python 变量类型
Python 运算符
Python 条件语句
Python 循环语句
Python While 循环语句
Python for 循环语句
Python 循环嵌套
Python break 语句
Python continue 语句
Python pass 语句
Python Number(数字)
Python 字符串
Python 列表(List)
Python 元组
Python 字典(Dictionary)
Python 日期和时间
Python 函数
Python 模块
Python 文件I/O
Python File 方法
Python 异常处理
Python OS 文件/目录方法
Python 内置函数
Python 高级教程Python 面向对象 Python 正则表达式 Python CGI 编程 Python MySQL Python 网络编程 Python SMTP Python 多线程 Python XML 解析 Python GUI 编程(Tkinter) Python2.x 与 3.x 版本区别 Python IDE Python JSON Python AI 绘画 Python 100例 Python 测验Python property() 函数描述property() 函数的作用是在新式类中返回属性值。 语法以下是 property() 方法的语法: class property([fget[, fset[, fdel[, doc]]]]) 参数
返回值返回新式类属性。 实例定义一个可控属性值 xclass 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.")
如果 c 是 C 的实例化, c.x 将触发 getter,c.x = value 将触发 setter , del c.x 触发 deleter。 如果给定 doc 参数,其将成为这个属性值的 docstring,否则 property 函数就会复制 fget 函数的 docstring(如果有的话)。 将 property 函数用作装饰器可以很方便的创建只读属性: class Parrot(object):
def __init__(self):
self._voltage = 100000
@property
def voltage(self):
"""Get the current voltage."""
return self._voltage
上面的代码将 voltage() 方法转化成同名只读属性的 getter 方法。 property 的 getter,setter 和 deleter 方法同样可以用作装饰器: 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
这个代码和第一个例子完全相同,但要注意这些额外函数的名字和 property 下的一样,例如这里的 x。
AI 思考中...
点我分享笔记取消
分类导航
Advertisement
|
| You are visitor 01402775 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |