一、什么是setter,getter
@property
的实现比较复杂,我们先考察如何使用。
把一个getter方法变成属性,只需要加上@property
就可以了,此时,@property
本身又创建了另一个装饰器@score.setter
,负责把一个setter方法变成属性赋值,于是,我们就拥有一个可控的属性操作.
refer to:https://www.geeksforgeeks.org/getter-and-setter-in-python/
二、使用场景
Case1:对属性的赋值做判断和异常检测
class Geeks: def __init__(self): self._age = 0 # using property decorator # a getter function @property def age(self): print("getter method called") return self._age # a setter function @age.setter def age(self, a): if a < 18: raise ValueError("Sorry you age is below eligibility criteria") print("setter method called") self._age = a # setting the age using setter if __name__ == ‘__main__‘: g = Geeks() age_before_set = g.age print(age_before_set) # 0 g.age = 19 age_after_set = g.age print(age_after_set) # 19
Case2:将 setter 和 getter 作为私有方法隐藏起来
class FinalClass: def __init__(self, var): ## calling the set_a() method to set the value ‘a‘ by checking certain conditions self.__set_a(var) ## getter method to get the properties using an object def __get_a(self): return self.__a ## setter method to change the value ‘a‘ using an object def __set_a(self, var): ## condition to check whether var is suitable or not if var > 0 and var % 2 == 0: self.__a = var else: self.__a = 2 a = property(__get_a, __set_a)
Case3:多种属性之间的动态依赖关系
refer to:https://iphysresearch.github.io/blog/post/programing/python/property_setter/