Python基础-@property
来源:互联网 发布:什么叫编程 编辑:程序博客网 时间:2024/05/29 03:08
@property
@property广泛应用在类的定义中,可以让调用者写出简短的代码,同时保证对参数进行必要的检查,这样,程序运行时就减少了出错的可能性。
示例代码
#!/usr/bin/env python3# -*- coding: utf-8 -*-# 使用@property# 颜值计算器class BeautifulValue(object): @property def score(self): return self._value # 这里相当于score函数的数值检测器,且名称要保持一致 @score.setter def score(self, value): if not isinstance(value, int): raise ValueError("must be integer data") if (value < 0) or (value > 10): raise ValueError("must between 0 ~ 10") self._value = valuedef testRun(): b = BeautifulValue(); b.score = 8 b.score = -1 #b.score = 100testRun()
运行结果
ValueError: must between 0 ~ 10
D:\PythonProject\sustudy>python main.pyTraceback (most recent call last): File "main.py", line 29, in <module> testRun() File "main.py", line 26, in testRun b.score = -1 File "main.py", line 18, in score raise ValueError("must between 0 ~ 10")ValueError: must between 0 ~ 10
阅读全文
0 0
- [基础] - Python中的@property
- Python基础-@property
- Python基础-@property
- 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
- 2017年度总结-2018总体规划
- 哈希学习代码
- 结构、枚举、数组
- hive中数据排序
- Tensorflow实例:实现深度强化学习--策略网络
- Python基础-@property
- 关系型数据库与NoSQL的对比
- pico i.MX7 Dual (I.MX7D)刷入AndroidThings
- MySQL installer 安装mysql5.7.20 和Connector/ODBC
- 图论基础知识总结(二)
- 伪知识之了解数据库中varchar(max) 和varchar(8000)的区别持续更新:【内向即失败--王奕君】
- Python错误AttributeError: 'module' object has no attribute 'copy'
- 给AI换个“大动力小心脏”之OCR异构加速
- mybatis对oracel LONG数据的处理