python中 @property
来源:互联网 发布:vb 调用bartender 编辑:程序博客网 时间:2024/05/22 14:26
Student 类:
class Student(object): def __init__(self, name, score): self.name = name self.score = score
当我们想要修改一个 Student 的 scroe 属性时,可以这么写:
s = Student('Bob', 59)s.score = 60
但是也可以这么写:
s.score = 1000
显然,直接给属性赋值无法检查分数的有效性。
如果利用两个方法:
class Student(object): def __init__(self, name, score): self.name = name self.__score = score def get_score(self): return self.__score def set_score(self, score): if score < 0 or score > 100: raise ValueError('invalid score') self.__score = score
这样一来,s.set_score(1000) 就会报错。
这种使用 get/set 方法来封装对一个属性的访问在许多面向对象编程的语言中都很常见。
但是写 s.get_score() 和 s.set_score() 没有直接写 s.score 来得直接。
有没有两全其美的方法?----有。
因为Python支持高阶函数,可以用装饰器函数把 get/set 方法“装饰”成属性调用:
class Student(object): def __init__(self, name, score): self.name = name self.__score = score @property def score(self): return self.__score @score.setter def score(self, score): if score < 0 or score > 100: raise ValueError('invalid score') self.__score = score
注意: 第一个score(self)是get方法,用@property装饰,第二个score(self, score)是set方法,用@score.setter装饰,@score.setter是前一个@property装饰后的副产品。
现在,就可以像使用属性一样设置score了:
>>> s = Student('Bob', 59)>>> s.score = 60>>> print s.score60>>> s.score = 1000Traceback (most recent call last): ...ValueError: invalid score
说明对 score 赋值实际调用的是 set方法。
阅读全文
0 0
- Python 中 property 用法
- python中 @property
- Python中@property
- python中 @property
- python中 @property
- python中@property的使用
- 在Python中动态绑定property
- 在Python中使用属性Property
- python中property函数的理解
- python中@property装饰器的用法
- python中@property与Descriptor的使用方法
- Python中@property的粗略理解
- 关于python中@property的使用
- 关于python中@property的使用
- python中property的使用实例
- python中@property装饰器的用法
- python -- property()/@property
- python @property
- shell与if相关参数
- 观察者模式
- java 项目中有汉字编译出来乱码问题
- snake
- 定位Oops错误代码行
- python中 @property
- Java中hashCode的作用
- maven命令学习
- fast rcnn中遇到的问题
- Java并发编程:volatile关键字解析
- 学习Python3:201701030
- 创建一个自己能写别人只能读的表
- 欢迎使用CSDN-markdown编辑器
- CodeForces 500C New Year Book Reading(贪心+思维)