一、什么是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)
重新设置属性值,用setter:
语法:
@property
def fun_name():
pass
@fun_name.setter()
def fun_name():
pass
class Student: """Class definition""" def __init__(self, *, name: str, score: int, mobile_number: str): """Init.""" self.name = name self.score = score self.mobile_number = mobile_number @property def mobile_number(self) -> str: """Message Counter (MCNT).""" return self._m_n @mobile_number.setter def mobile_number(self, new_number: str): if len(new_number) != 11: raise ValueError("Invalid message counter.") self._m_n = new_number if __name__ == '__main__': zhangsan = Student(name="zhangsan", score=90, mobile_number="13099998888") print(zhangsan.mobile_number) # 13099998888 zhangsan.mobile_number = "13144449999" print(zhangsan.mobile_number) # 13144449999