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的用法详解