美文网首页
Python:11.使用@property

Python:11.使用@property

作者: 许瘦子来世 | 来源:发表于2018-07-11 17:07 被阅读8次
# @property
'''
1. 把一个getter方法变成属性,只需要加上@property就可以了。
此时,@property本身又创建了另一个装饰器@score.setter,负责把一个setter方法变成属性赋值。

2. 定义只读属性:只定义getter方法,不定义setter方法
'''
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 - 1001')
        self._score = value

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

相关文章

网友评论

      本文标题:Python:11.使用@property

      本文链接:https://www.haomeiwen.com/subject/rxahpftx.html