ITS·黑客

【python】把方法变成属性调用 @property

2017-05-11  本文已影响22人  某米狼

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

class Student(object):

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

    @score.setter
    def score(self, value):
  # 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.score = 60 # 实际转化为s.set_score(60)
>>> s.score # 实际转化为s.get_score()
60
>>> s.score = 9999 # s.set_score(9999)
Traceback (most recent call last):
  ...
ValueError: score must between 0 ~ 100!

只给 @property 不给@xx.setter 就相当于只读属性

上一篇 下一篇

猜你喜欢

热点阅读