python @property
来源:互联网 发布:朗文英语词典知乎 编辑:程序博客网 时间:2024/06/03 14:21
有时候我们需要对类属性的值进行一些限制,例如人的身高要大于0
此时,符合 Python 风格的做法是,把数据属性换成特性。
class Person: def __init__(self, height): self.height = height# 初始化赋值给特性 @property# 装饰读值方法 def height(self):# 特性方法与名称一样 return self._height# 真正存身高的变量 @height.setter# 读值方法修饰器 def height(self, value):# 读值方法要与特性名称一直 if value > 0: self._height = value# 身高 > 0 else: raise Exception('height muste > 0') @height.deleter# 删除特性操作修饰器 def height(self): self._height = 0>>> p = Person(-180)Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<stdin>", line 3, in __init__ File "<stdin>", line 12, in heightException: height muste > 0>>> p = Person(180)>>> p.height180>>> del p.height>>> p.height0
阅读全文
0 0
- python -- property()/@property
- python @property
- Python @property
- Python @property
- Python @property
- python @property
- python Property
- Python @property
- python property
- python property
- python @property
- Python @property
- python property
- python property
- Python @property
- python-property
- python @property
- python @property
- Just another Robbery(概率dp)
- 网卡信息小程序
- 学习廖大的JS--第一节
- seetaface
- Android性能测试用例
- python @property
- Oracle 字段值的空或非空判断,兼容MySQL
- OpenGL+VS2015+WIN10 demo
- 洛谷 新手村 数组 校门外的树
- C++primer第一章习题
- LeetCode515
- iOS之热修复JSPatch 补丁更新管理
- 黄页模块phpcms
- 使用dom4j解析xml文件,并封装为javabean对象