Python内置函数(63)——property
英文文档:
class property(fget=None, fset=None, fdel=None, doc=None)
Return a property attribute.
fget is a function for getting an attribute value. fset is a function for setting an attribute value. fdel is a function for deleting an attribute value. And doc creates a docstring for the attribute.
If given, doc will be the docstring of the property attribute. Otherwise, the property will copy fget‘s docstring (if it exists). This makes it possible to create read-only properties easily using property() as a decorator。
The @property decorator turns the voltage() method into a “getter” for a read-only attribute with the same name, and it sets the docstring for voltage to “Get the current voltage.”
A property object has getter, setter, and deleter methods usable as decorators that create a copy of the property with the corresponding accessor function set to the decorated function.
显示属性的装饰器
说明:
1. property是一个类,其作用是用来包装类的属性,这个属性可以根据实际需要,控制是否可读(设置fget参数)、可写(设置fset参数)、可删除(设置fdel参数)。
class C:
def __init__(self):
self._x = '_x in C' 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 # 调用 getx
'_x in C' >>> c.x = 'x had changed' # 调用 setx
>>> c.x # 调用 getx
'x had changed' >>> del c.x # 调用 delx
>>> c.x # 调用 getx
Traceback (most recent call last):
File "<pyshell#34>", line 1, in <module>
c.x
File "<pyshell#28>", line 6, in getx
return self._x
AttributeError: 'C' object has no attribute '_x'
2. 参数doc表示的是属性的说明,如果没有指定,将从fget参数指定的方法中读取。
Help on C in module __main__ object: class C(builtins.object)
| Methods defined here:
|
| __init__(self)
| Initialize self. See help(type(self)) for accurate signature.
|
| delx(self)
|
| getx(self)
|
| setx(self, value)
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables (if defined)
|
| __weakref__
| list of weak references to the object (if defined)
|
| x
| I'm the 'x' property. # 最后一行中 文档字符串 为I'm the 'x' property. >>> class C:
def __init__(self):
self._x = '_x in C' def getx(self):
"""I'm the 'x' property. provide by getx"""
return self._x def setx(self, value):
self._x = value def delx(self):
del self._x x = property(getx, setx, delx) >>> help(C)
Help on class C in module __main__: class C(builtins.object)
| Methods defined here:
|
| __init__(self)
| Initialize self. See help(type(self)) for accurate signature.
|
| delx(self)
|
| getx(self)
| I'm the 'x' property. provide by getx
|
| setx(self, value)
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables (if defined)
|
| __weakref__
| list of weak references to the object (if defined)
|
| x
| I'm the 'x' property. provide by getx # 最后一行中 文档字符串 为 I'm the 'x' property. provide by getx
3. property更优雅的做法是用作装饰器,装饰过的方法就可以以属性方式调用。同时将生成.setter和.deleter装饰器,用于指定可入方法,删除方法。
>>> class C:
def __init__(self):
self._x = '_x in C' @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
>>> c = C()
>>> c.x # 调用 getx
'_x in C' >>> c.x = 'x had changed' # 调用 setx
>>> c.x # 调用 getx
'x had changed' >>> del c.x # 调用 delx
>>> c.x # 调用 getx
Traceback (most recent call last):
File "<pyshell#34>", line 1, in <module>
c.x
File "<pyshell#28>", line 6, in getx
return self._x
AttributeError: 'C' object has no attribute '_x'
4. 不直接使用字段,而使用属性,主要因为可以控制外部对类字段的恶意修改和删除,而且可以再设置属性值的时候进行适当的验证。
>>> class C:
def __init__(self):
self._name = ''
@property
def name(self):
"""i'm the 'name' property."""
return self._name
@name.setter
def name(self,value):
if value is None:
raise RuntimeError('name can not be None')
else:
self._name = value >>> c = C() >>> c.name # 访问属性
''
>>> c.name = None # 设置属性时进行验证
Traceback (most recent call last):
File "<pyshell#84>", line 1, in <module>
c.name = None
File "<pyshell#81>", line 11, in name
raise RuntimeError('name can not be None')
RuntimeError: name can not be None >>> c.name = 'Kim' # 设置属性
>>> c.name # 访问属性
'Kim' >>> del c.name # 删除属性,不提供deleter则不能删除
Traceback (most recent call last):
File "<pyshell#87>", line 1, in <module>
del c.name
AttributeError: can't delete attribute
>>> c.name
'Kim'
Python内置函数(63)——property的更多相关文章
- Python内置函数之-property
property 是一个内置的装饰器函数,只在面向对象中使用 求一个圆的周长和面积 # 周长和面积都是通过类的方法得到from math import pi class Cricle: def __i ...
- Python内置函数(63)——super
英文文档: super([type[, object-or-type]]) Return a proxy object that delegates method calls to a parent ...
- Python内置函数(51)——property
英文文档: class property(fget=None, fset=None, fdel=None, doc=None) Return a property attribute. fget is ...
- python内置函数详细介绍
知识内容: 1.python内置函数简介 2.python内置函数详细介绍 一.python内置函数简介 python中有很多内置函数,实现了一些基本功能,内置函数的官方介绍文档: https: ...
- Python | 内置函数(BIF)
Python内置函数 | V3.9.1 | 共计155个 还没学完, 还没记录完, 不知道自己能不能坚持记录下去 1.ArithmeticError 2.AssertionError 3.Attrib ...
- Python 内置函数笔记
其中有几个方法没怎么用过, 所以没整理到 Python内置函数 abs(a) 返回a的绝对值.该参数可以是整数或浮点数.如果参数是一个复数,则返回其大小 all(a) 如果元组.列表里面的所有元素都非 ...
- python内置函数大全(分类)
python内置函数大全 python内建函数 最近一直在看python的document,打算在基础方面重点看一下python的keyword.Build-in Function.Build-in ...
- Python内置函数7
Python内置函数7 1.propertypython内置的一个装饰器可参考https://blog.csdn.net/u013205877/article/details/77804137 2.q ...
- Python内置函数6
Python内置函数6 1.license() 输出当前python 的license信息 A. HISTORY OF THE SOFTWARE ========================== ...
随机推荐
- Android 的自动化测试资源
环境预备阶段: win7下jdk+eclipse android应用开发环境建立 android genymotion模拟器怎么使用以及和google提供的模拟器性能对比
- table_rows查询优化
日常应用运维工作中,Dev或者db本身都需要统计表的行数,以此作为应用或者维护的一个信息参考.也许很多人会忽略select count(*) from table_name类似的sql对数据库性能的影 ...
- Filecoin2017年Q4进度更新(完整版)
亲爱的Filecoin支持者.矿工.用户.投资者和广大的社区朋友们, 自从Token销售完成以后,我们便开始集中精力把Filecoin项目从设想变为现实-从实现Filecoin协议的核心代码到打造我们 ...
- EOS 上线前,先搞懂这两个基本概念
如果你曾经尝试在本地运行 EOS 测试节点,会发现编译.运行并不是特别复杂,但官方教程里两个概念很容易把人搞晕: Account(账户)和 Wallet (钱包). EOS 的 Wallet 跟其他区 ...
- macOS下利用dSYM文件将crash文件中的内存地址转换为可读符号
一.使用流程 Windows下的程序运行崩溃时,往往可以利用pdb文件快速解析出程序崩溃的具体位置,甚至可以对应到源代码的具体行数.macOS下的symbolicatecrash也具备相应的功能.对应 ...
- workflow--相关笔记
转自http://blog.csdn.net/u014682573/article/details/29922093 1. 工作流技术 工作流(Workflow) 定义:工作流就是将一组任务组织起来, ...
- ngix_http_stub_status_module
1.ngx_http_stub_status_module 是一个 Nginx 的内置 HTTP 模块,该模块可以提供 Nginx 的状态信息.默认情况下这个模块是不被编译进来的,所以在编译 Ngin ...
- 设计模式 --> (17)状态模式
状态模式 允许一个对象在其内部状态改变时改变它的行为.对象看起来似乎修改了它的类.它有两种使用情况: (1)一个对象的行为取决于它的状态, 并且它必须在运行时刻根据状态改变它的行为. (2)一个操作中 ...
- [poj2406]Power Strings_hash
Power Strings poj-2406 题目大意:询问一个字符串最多几个相同且连续的字符串构成(Eg:abababab由4个构成,abcd由1个构成). 注释:字符串长度为n,$1\le n\l ...
- 关于使用Unity开发Kinect时出现的Runtime Error错误的解决方式
一.开发环境: 1. 硬件:Kinect 2.0 2. 操作系统:Windows10 3. Unity版本:5.x以上 4. Kinect SDK:KinectSDK-v2.0_1409 5. Kin ...