python基础——使用@property
python基础——使用@property
在绑定属性时,如果我们直接把属性暴露出去,虽然写起来很简单,但是,没办法检查参数,导致可以把成绩随便改:
s = Student()
s.score = 9999
这显然不合逻辑。为了限制score的范围,可以通过一个set_score()方法来设置成绩,再通过一个get_score()来获取成绩,这样,在set_score()方法里,就可以检查参数:
class Student(object):
def get_score(self):
return self._score
def set_score(self, value):
if not isinstance(value, int):
raise ValueError('score must be an integer!')
if value < 0 or value > 100:
raise ValueError('score must between 0 ~ 100!')
self._score = value
现在,对任意的Student实例进行操作,就不能随心所欲地设置score了:
>>> s = Student()
>>> s.set_score(60) # ok!
>>> s.get_score()
60
>>> s.set_score(9999)
Traceback (most recent call last):
...
ValueError: score must between 0 ~ 100!
但是,上面的调用方法又略显复杂,没有直接用属性这么直接简单。
有没有既能检查参数,又可以用类似属性这样简单的方式来访问类的变量呢?对于追求完美的Python程序员来说,这是必须要做到的!
还记得装饰器(decorator)可以给函数动态加上功能吗?对于类的方法,装饰器一样起作用。Python内置的@property装饰器就是负责把一个方法变成属性调用的:
class Student(object):
@property
def score(self):
return self._score
@score.setter
def score(self, value):
if not isinstance(value, int):
raise ValueError('score must be an integer!')
if value < 0 or value > 100:
raise ValueError('score must between 0 ~ 100!')
self._score = value
@property的实现比较复杂,我们先考察如何使用。把一个getter方法变成属性,只需要加上@property就可以了,此时,@property本身又创建了另一个装饰器@score.setter,负责把一个setter方法变成属性赋值,于是,我们就拥有一个可控的属性操作:
>>> s = Student()
>>> s.score = 60 # OK,实际转化为s.set_score(60)
>>> s.score # OK,实际转化为s.get_score()
60
>>> s.score = 9999
Traceback (most recent call last):
...
ValueError: score must between 0 ~ 100!
注意到这个神奇的@property,我们在对实例属性操作的时候,就知道该属性很可能不是直接暴露的,而是通过getter和setter方法来实现的。
还可以定义只读属性,只定义getter方法,不定义setter方法就是一个只读属性:
class Student(object):
@property
def birth(self):
return self._birth
@birth.setter
def birth(self, value):
self._birth = value
@property
def age(self):
return 2015 - self._birth
上面的birth是可读写属性,而age就是一个只读属性,因为age可以根据birth和当前时间计算出来。
小结
@property广泛应用在类的定义中,可以让调用者写出简短的代码,同时保证对参数进行必要的检查,这样,程序运行时就减少了出错的可能性。
练习
请利用@property给一个Screen对象加上width和height属性,以及一个只读属性resolution:
代码:
#练习:
'''
请利用@property给一个Screen对象加上width和height属性,
以及一个只读属性resolution
'''
class Screen(object): @property
def width(self):
return self._width @width.setter
def width(self,value):
if not isinstance(value,int):
raise ValueError('width must be an integer!')
elif value<=0:
raise ValueError('width must greater than zero!')
self._width=value @property
def height(self):
return self._height @height.setter
def height(self,value):
if not isinstance(value,int):
raise ValueError('height must be an integer!')
elif value<=0:
raise ValueError('height must greater than zero!')
self._height=value @property
def resolution(self):
return (self._width * self._height) tv=Screen()
tv.width=1024
tv.height=768
print('tv.width=',tv.width)
print('tv.height=',tv.height) try:
tv.resolution=10000
except AttributeError as e:
print('AttributeError:',e) print(tv.resolution) #
assert tv.resolution == 786432, '1024 * 768 = %d ?' % tv.resolution
运行结果:

python基础——使用@property的更多相关文章
- Python基础(@property)
class Point(object): # def get_score(self): # return self.score # def set_score(self,value): # if no ...
- python基础——特性(property)、静态方法(staticmethod)和类方法(classmethod)
python基础--特性(property) 1 什么是特性property property是一种特殊的属性,访问它时会执行一段功能(函数)然后返回值 import math class Circl ...
- python基础-abstractmethod、__属性、property、setter、deleter、classmethod、staticmethod
python基础-abstractmethod.__属性.property.setter.deleter.classmethod.staticmethod
- Python之路【第二篇】:Python基础
参考链接:老师 BLOG : http://www.cnblogs.com/wupeiqi/articles/4906230.html 入门拾遗 一.作用域 只要变量在内存中就能被调用!但是(函数的栈 ...
- python基础——面向对象编程
python基础——面向对象编程 面向对象编程——Object Oriented Programming,简称OOP,是一种程序设计思想.OOP把对象作为程序的基本单元,一个对象包含了数据和操作数据的 ...
- Python自动化 【第七篇】:Python基础-面向对象高级语法、异常处理、Scoket开发基础
本节内容: 1. 面向对象高级语法部分 1.1 静态方法.类方法.属性方法 1.2 类的特殊方法 1.3 反射 2. 异常处理 3. Socket开发基础 1. ...
- Python基础(二) —— 字符串、列表、字典等常用操作
一.作用域 对于变量的作用域,执行声明并在内存中存在,该变量就可以在下面的代码中使用. 二.三元运算 result = 值1 if 条件 else 值2 如果条件为真:result = 值1如果条件为 ...
- Python基础教程【读书笔记】 - 2016/7/31
希望通过博客园持续的更新,分享和记录Python基础知识到高级应用的点点滴滴! 第十波:第10章 充电时刻 Python语言的核心非常强大,同时还提供了更多值得一试的工具.Python的标准安装包括 ...
- Python基础教程【读书笔记】 - 2016/7/24
希望通过博客园持续的更新,分享和记录Python基础知识到高级应用的点点滴滴! 第九波:第9章 魔法方法.属性和迭代器 在Python中,有的名称会在前面和后面都加上两个下划线,这种写法很特别.已 ...
随机推荐
- post 之checkbox 未被选中解决方法
第一种方法: http://cnn237111.blog.51cto.com/2359144/1293812 第二种方法(推荐): http://blog.csdn.net/xyanghomepage ...
- XML文件数据操作
#region XML序列化文件和反序列化 /// <summary> /// 通用类的保存函数,可以将已经声明过可序列化的类以文件方式保存起来. /// 保存格式分为 XML明文式和 二 ...
- FineUI第十六天---表格的排序和分页
表格的排序和分页 1.表格的排序需要: AllowSorting:是否允许排序. SortColumn:当前排序的列ID,当然也可以不设置此属性,而是在后台初始化代码中直接指定默认排序字段. Sort ...
- iOS开发——UI进阶篇(二)自定义等高cell,xib自定义等高的cell,Autolayout布局子控件,团购案例
一.纯代码自定义等高cell 首先创建一个继承UITableViewCell的类@interface XMGTgCell : UITableViewCell在该类中依次做一下操作1.添加子控件 - ( ...
- 分析Masonry
一. 继承关系 1.MASConstraint (abstract) MASViewContraint MASComposisionConstraint 2. UIView NSLayoutConst ...
- git 教程(7)--撤销修改
自然,你是不会犯错的.不过现在是凌晨两点,你正在赶一份工作报告,你在readme.txt中添加了一行:
- union联合体
今天笔试的一道题,好久没用union了,竟然忘光光了. 关于其大小的计算,分两步:先算对齐大小(成员中字节最大的那个),再算分配空间: 不仅是对齐大小的整数倍,还要满足实际大小不能小于最大成员大小. ...
- ubuntu系统安装PHP扩展
GD库的安装 sudo apt-get install php5-gd sudo apt-get install php5-gd sudo /etc/init.d/apache2 restart CU ...
- c++ SOA Axis2c 编译安装
Axis2C 安装过程 1设置环境变量 export AXIS2C_HOME=/usr/local/axis2c 2.下载源码包解压编译安装 cd axis2c-src-1.6.0 ./configu ...
- Js 的 this 是什么
this指的是调用函数的那个对象,谁调用函数,谁就是this 更多: http://www.cnblogs.com/justany/archive/2012/11/01/the_keyword_thi ...