python中property函数_python中的property属性

1. 基本认识

property属性可以用来给属性添加约束,比如温度属性,我们不允许低于-273度;成绩属性,我们不允许0分以下等等。而且使用property属性,将来修改约束条件的时候也很方便,可以在代码的调用方式不变的情况下改变结果。

python中使用property属性有两种方法。使用@property装饰器和使用property()函数。

我们通过廖雪峰官方网站的实例来对此加深认识。

2. @property装饰器

@property装饰器就是负责把一个方法变成属性调用的。如下实例就可以通过s.score来获得成绩,并且对score赋值之前做出了数据检查。

classStudent(object):def __init__(self, score=0):

self._score=score

@propertydefscore(self):print("getting score")returnself._score

@score.setterdefscore(self, value):print("setting score")if notisinstance(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

s= Student(60)

s.scoreprint("=====================")

s.score= 88s.score

3. property()函数

python中关于property()函数的介绍如下,在jupyter notebook中输入property??,即可查看用法:

1600350-20190720102406307-548367407.png

从帮助中可以看出,property()函数可以接收4个参数,第一个参数对应获取,第二个参数对应设置,第三个参数对应删除,第四个参数对应注释,写法如下:

classStudent(object):def __init__(self, score=0):

self._score=scoredefget_score(self):print("getting score")returnself._scoredefset_score(self, value):print("setting score")if notisinstance(value, int):raise ValueError("score must be an integer!")if value < 0 or value > 100:raise ValueError('score must between 0 ~ 100!')

self._score=valuedefdel_score(self):print("delete score")delself._score

score=property(get_score, set_score, del_score)

s= Student(60)print(s.score)print("=====================")

s.score= 88

print(s.score)print("=====================")del s.score

参考链接:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值