Python @property使用方法解析
作者:bob_coder 时间:2021-10-27 05:42:46
1. 作用
将类方法转换为类属性,可以用 . 直接获取属性值或者对属性进行赋值
2.实现方式
使用property类来实现,也可以使用property装饰器实现,二者本质是一样的。多数情况下用装饰器实现。
class Student(object):
@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
student = Student()student.score = 65print(student.score)65
score()方法上增加@property装饰器,等同于score= property(fget=score),将score赋值为property的实例。
所以,被装饰后的score,已经不是这个实例方法score了,而是property的实例score。
来源:https://www.cnblogs.com/bob-coder/p/11532718.html
标签:python,@property,方法
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
SQL Server上进行表设计时表的主键设计问题
2010-06-24 16:10:00
PDO::quote讲解
2023-06-03 21:14:37
使用Pyinstaller转换.py文件为.exe可执行程序过程详解
2022-11-30 22:43:40
![](https://img.aspxhome.com/file/2023/8/79728_0s.png)
CSS 设计中的黄金分割率应用
2008-11-12 12:17:00
![](https://img.aspxhome.com/file/UploadPic/200811/12/u2008111121121-91s.png)
小谈用户身体语言的阅读经验
2009-10-19 20:52:00
![](https://img.aspxhome.com/file/UploadPic/200910/19/bodylanguage-banner-72s.jpg)
firefox通过XUL实现text-overflow:ellipsis的效果
2008-07-08 19:12:00
三种SQL分页查询的存储过程代码
2012-01-05 19:31:32
tensorflow 动态获取 BatchSzie 的大小实例
2023-03-05 16:56:48
![](https://img.aspxhome.com/file/2023/8/81518_0s.jpg)
[新手必看]15个asp编程常见问题解答
2007-08-22 13:07:00
![](https://img.aspxhome.com/file/UploadPic/up/2007082213545326.jpg)
Python绘制词云图之可视化神器pyecharts
2023-02-23 01:35:25
![](https://img.aspxhome.com/file/2023/9/69449_0s.png)
搜索结果页(SERP)之:不要被F型浏览忽悠了
2009-09-07 12:34:00
![](https://img.aspxhome.com/file/UploadPic/20099/7/jakob-nielsen-58s.jpg)
PHP global全局变量经典应用与注意事项分析【附$GLOBALS用法对比】 <font color=red>原创</font>
2023-11-16 07:37:55
Javascript中的isNaN函数使用说明
2023-08-27 10:10:02
python分块读取大数据,避免内存不足的方法
2022-09-30 13:05:17
es6函数之严格模式用法实例分析
2023-08-09 06:15:40
python3实现163邮箱SMTP发送邮件
2021-02-28 07:59:19
![](https://img.aspxhome.com/file/2023/8/63538_0s.jpg)
css基础教程属性篇之二
2008-07-25 19:23:00
![](https://img.aspxhome.com/file/UploadPic/20087/25/2008725192720609s.jpg)
Django实现将views.py中的数据传递到前端html页面,并展示
2022-04-04 10:44:56
![](https://img.aspxhome.com/file/2023/2/72262_0s.jpg)
matplotlib设置legend图例代码示例
2023-04-18 13:20:12
![](https://img.aspxhome.com/file/2023/5/78515_0s.jpg)
Python 输出时去掉列表元组外面的方括号与圆括号的方法
2023-06-06 07:10:44
![](https://img.aspxhome.com/file/2023/9/65499_0s.jpg)