【Python】@property的使用

解决的问题:在对输入的数据进行限制的同时,对该函数能够像调用类中的对象一样方便

参考链接

@廖雪峰
@人生与戏
@北方卧龙

使用方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class test:
def __init__(self):
self.__s =60
@property #加上@property修饰器
def score(self):
return self.__s
@score.setter
def score(self,value):
if value < 0 or value > 100:
raise ValueError('分数必须介于0-100之间')
self.__s=value
def setscore(self,value):
if value < 0 or value > 100:
raise ValueError('分数必须介于0-100之间')
self.__s=value
p=test()

输出结果

1
2
3
4
5
6
7
8
9
10
11
12
p.score
Out[55]: 60

p.setscore(80) #不使用property的调用

p.score
Out[57]: 80

p.score=100 #使用了property和setter的调用

p.score
Out[59]: 100