python基础===装饰器@property 的扩展
- 以下来自Python 3.6.0 Document:
- 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.
A typical use is to define a managed attribute
x:class C:
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.")If c is an instance of C,
c.xwill invoke the getter,c.x = valuewill invoke the setter anddel c.xthe deleter.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:class Parrot:
def __init__(self):
self._voltage = 100000 @property
def voltage(self):
"""Get the current voltage."""
return self._voltageThe
@propertydecorator turns thevoltage()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, anddeletermethods usable as decorators that create a copy of the property with the corresponding accessor function set to the decorated function. This is best explained with an example: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._xThis code is exactly equivalent to the first example. Be sure to give the additional functions the same name as the original property (
xin this case.)The returned property object also has the attributes
fget,fset, andfdelcorresponding to the constructor arguments.Changed in version 3.5: The docstrings of property objects are now writeable.
先看一段代码:
class stu:
def __init__(self,name):
self.name = name def get_score(self):
return self.score def set_score(self, score):
if not isinstance(score, int):
raise ValueError("score must be an integer~")
if score>100 or score<0:
raise ValueError("score must between 0~100")
self.score = score s = stu("Botoo")
#s.set_score(100) #score must be an integer~
#s.set_score("dasda") #score must between 0~100
s.set_score(98)
print(s.get_score()) #
这种使用 get/set 方法来封装对一个属性的访问在许多面向对象编程的语言中都很常见。
但是写 s.get_score() 和 s.set_score() 没有直接写 s.score 来得直接。
因为Python支持高阶函数,可以用装饰器函数把 get/set 方法“装饰”成属性调用:
再比较:
class Student:
def __init__(self,name):
self.name = name @property
def score(self):
return self._score @score.setter
def score(self,value):
if not isinstance(value, int):
raise ValueError('分数必须是整数才行呐')
if value < 0 or value > 100:
raise ValueError('分数必须0-100之间')
self._score = value S1 = Student("botoo")
S1.score = 50 print(S1.score) #
S1.score = 500 #ValueError: 分数必须0-100之间
第一个score(self)是get方法,用@property装饰,第二个score(self, score)是set方法,用@score.setter装饰,@score.setter是前一个@property装饰后的副产品。
在子类中扩展一个property可能会引起很多不易察觉的问题, 因为一个property其实是 getter、setter 和 deleter 方法的集合,而不是单个方法。 因此,当你扩展一个property的时候,你需要先确定你是否要重新定义所有的方法还是说只修改其中某一个。
- 只有@property表示只读。
- 同时有@property和@x.setter表示可读可写。
- 同时有@property和@x.setter和@x.deleter表示可读可写可删除。
参考:
http://python3-cookbook.readthedocs.io/zh_CN/latest/c08/p08_extending_property_in_subclass.html
https://blog.csdn.net/u013205877/article/details/77804137
https://blog.csdn.net/sxingming/article/details/52916249
python基础===装饰器@property 的扩展的更多相关文章
- python基础——装饰器
python基础——装饰器 由于函数也是一个对象,而且函数对象可以被赋值给变量,所以,通过变量也能调用该函数. >>> def now(): ... print('2015-3-25 ...
- python基础—装饰器
python基础-装饰器 定义:一个函数,可以接受一个函数作为参数,对该函数进行一些包装,不改变函数的本身. def foo(): return 123 a=foo(); b=foo; print(a ...
- python 基础——装饰器
python 的装饰器,其实用到了以下几个语言特点: 1. 一切皆对象 2. 函数可以嵌套定义 3. 闭包,可以延长变量作用域 4. *args 和 **kwargs 可变参数 第1点,一切皆对象,包 ...
- day5学python 基础+装饰器内容
基础+装饰器内容 递归特性# 1.必须有一个明确的结束条件# 2.每次进入更深一层递归时,问题规模相比上次递归应有所减少# 3.递归效率不高 def run(n): print(n) if int(n ...
- python基础 (装饰器,内置函数)
https://docs.python.org/zh-cn/3.7/library/functions.html 1.闭包回顾 在学习装饰器之前,可以先复习一下什么是闭包? 在嵌套函数内部的函数可以使 ...
- <Python基础>装饰器的基本原理
1.装饰器 所谓装饰器一般是对已经使用(上线)的函数增加功能. 但是因为一般的大公司的严格按照开放封闭原则(对扩展是开放的,对修改是封闭的),不会让你修改原本的函数. 装饰器就是在不改变原本的函数且不 ...
- Python自动化 【第四篇】:Python基础-装饰器 生成器 迭代器 Json & pickle
目录: 装饰器 生成器 迭代器 Json & pickle 数据序列化 软件目录结构规范 1. Python装饰器 装饰器:本质是函数,(功能是装饰其它函数)就是为其他函数添加附加功能 原则: ...
- python基础-装饰器,生成器和迭代器
学习内容 1.装饰器 2.生成器 3.迭代器 4.软件目录结构规范 一:装饰器(decorator) 1.装饰器定义:本质就是函数,用来装饰其他函数,即为其他函数添加附加功能. 2.装饰器原则:1)不 ...
- python基础-装饰器
一.什么是装饰器 装饰器本质就是函数,功能是为其他函数附加功能 二.装饰器遵循的原则 1.不修改被修饰函数的源代码 2.不修改被修饰函数的调用方式 三.实现装饰器的知识储备 装饰器=高阶函数+函数嵌套 ...
随机推荐
- service(ServletRequest req, ServletResponse res) 通用servlet 可以接受任意类型的请求 用于扩展
service(ServletRequest req, ServletResponse res) 通用servlet 可以接受任意类型的请求 用于扩展
- Luogu3147 USACO16OPEN 262144(动态规划)
感觉上这个题是可以直接暴力的,每次根据一段连续最小值个数的奇偶性决定是否划分区间,递归处理.然而写起来实在太麻烦了. 设f[i][j]为以i为左端点合并出j时的右端点.则有f[i][j]=f[f[i] ...
- BZOJ3143:[HNOI2013]游走——题解
http://www.lydsy.com/JudgeOnline/problem.php?id=3143 Description 一个无向连通图,顶点从1编号到N,边从1编号到M. 小Z在该图上进行随 ...
- CF498D:Traffic Jams in the Land——题解
https://vjudge.net/problem/CodeForces-498D http://codeforces.com/problemset/problem/498/D 题面描述: 一些国家 ...
- ContestHunter暑假欢乐赛 SRM 01 - 儿童节常数赛 爆陵记
最后15min过了两题...MDZZ 果然是不适合OI赛制啊...半场写完三题还自信满满的,还好有CZL报哪题错了嘿嘿嘿(这算不算犯规了(逃 悲惨的故事*1....如果没有CZL的话T1 10分 悲惨 ...
- [AHOI2008] 逆序对
link 我们可以很容易的推断出$-1$是单调不降的,若$i>j$且$a_i$与$a_j$都没有填数,若填完之后$a_i>a_j$或者$a_i<a_j$,则对答案产生影响的只在$[i ...
- ioctl函数用法小记
By francis_hao Aug 27,2017 UNPV1对ioctl有算是比较详细的介绍,但是,这些request和后面的数据类型是从哪里来的,以及参数具体该如何使用呢?本文尝试在不 ...
- 第六章 指针与const
const一词在字面上来源于常量constant,const对象在C/C++中是有不同解析的,如第二章所述,在C中常量表达式必须是编译期,运行期的不是常量表达式,因此C中的const不是常量表达式:但 ...
- HTTP的特点?
(1)HTTP是无连接: 无连接的含义是限制每次连接只处理一个请求.服务器处理完客户的请求,并收到客户的应答后,即断开连接.采用这种方式可以节省传输时间. (2)HTTP是媒体独立的: 这意味着,只要 ...
- ASP.NET创建三层架构图解详细教程
1.新建项目 2.创建Visual Studio解决方案 3.再创建项目 4.选择类库类型 5.依次创建bll(业务逻辑层),dal(数据访问层)和model(模型层也可以叫实体层) 6.添加一个网站 ...