1. 要解决的问题: 想要快速的访问类中的私有属性,但是不想直接暴露出原来类中的属性
@property
def tick(self):
return self._tick
2. 经典例子
# property decorator make defining and modifying class‘s property easy class Student: @property def score(self): return self.__score @score.setter def score(self, score): if isinstance(score, int): self.__score = score else: print(‘score must be int‘) if __name__ == ‘__main__‘: s = Student() s.score = ‘a‘ # 直接使用类的方法名字, 而不是直接使用类的属性 print(s.score)
3. 直接使用类的方法名字, 而不是直接使用类的属性
class Student: def __init__(self, score): self._score = score @property def return_score(self): return self._score if __name__ == ‘__main__‘: s = Student(5) print(s.return_score)
参考: https://www.cnblogs.com/linuxchao/p/linuxchao-property.html
原文:https://www.cnblogs.com/hixiaowei/p/14392671.html