@property使用

1.介绍

将类方法转换为类属性,可以用.直接获取属性值或者对属性进行赋值
Python内置的@property装饰器就是负责把一个方法变成属性调用的

2. 实现

class student(object):
    @property
    def score(self):
        return self._score
    @score.setter
    def score(self,value):
        if not isinstance(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
stu=student()
stu.score=99
print(stu.score)

3. 总结

score()方法上增加@property装饰器,等同于score= property(fget=score),将score赋值为property的实例。

所以,被装饰后的score,已经不是这个实例方法score了,而是property的实例score。

@property广泛应用在类的定义中,可以让调用者写出简短的代码,同时保证对参数进行必要的检查,这样,程序运行时就减少了出错的可能性。

猜你喜欢

转载自www.cnblogs.com/Ink-kai/p/12425860.html
今日推荐