python @property

来源:互联网 发布:高仿lv男包淘宝店 编辑:程序博客网 时间:2024/06/10 15:30
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 int")        if value < 0 or value >100:            raise ValueError("score must between 0 and 100")        self._score = values = Student()s.score = 10print s.score########10

Python内置的@property装饰器就是负责把一个方法变成属性调用

两个函数的方法名要相同

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


0 0
原创粉丝点击