Python:装饰器在类中的简单理解

/ Python / 没有评论 / 2029浏览

1.先上一个例子:

class Student(object):

    def get_score(self):
         return self._score

    def set_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
#调用
s = Student()
s.set_score = 89
print s.get_score()
这是一个实例,写了get()和set()方法,这是没有使用装饰器写法

2.通过装饰器的修饰将python类中方法转换成属性

class Student(object):

    @property    
    def score(self):
        return self._score

    @score.setter     #相当于set(),@property相当于get()
    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

#调用
s = Student()
s.score = 78
print s.score