装饰器 使用@property

2023-05-16,,

转载:https://www.liaoxuefeng.com/wiki/0014316089557264a6b348958f449949df42a6d3a2e542c000/00143186781871161bc8d6497004764b398401a401d4cce000

@property@XXX.setter
br/>@XXX.setter<br/设置一个可读写属性

仅使@property,设置一个只读属性

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

使用@property后,调用函数变为函数名称的属性赋值、读取

s.score = 60 # OK,实际转化为s.set_score(60)
s.score # OK,实际转化为s.get_score()

《装饰器 使用@property.doc》

下载本文的Word格式文档,以方便收藏与打印。