@property可以将一个方法的调用方式编程‘属性调用’:
class E: @property def salary(self): print('salary run.....') return 10000 e=E() print(e.salary) #这里salary变成了属性调用,以前要e.salary()这样调用 #e.salary=20000 #AttributeError: can't set attribute 报错,不能设置 结果 salary run..... 10000
class Emploree: def __init__(self,name,salary): self.__name=name self.__salary=salary def get_salary(self): return self.__salary def set_salary(self,salary): if 1000<salary<50000: self.__salary=salary else: print('错误,重新输入') emp1=Emploree('Jim',2000) emp1.set_salary(999) 结果: 错误,重新输入
下面换@property
class Emploree: def __init__(self,name,salary): self.__name=name self.__salary=salary @property def salary(self): return self.__salary @salary.setter def salary(self,salary): if 1000 < salary < 50000: self.__salary = salary else: print('错误,重新输入') ''' def get_salary(self): return self.__salary def set_salary(self,salary): if 1000<salary<50000: self.__salary=salary else: print('错误,重新输入') ''' emp1=Emploree('Jim',2000) print(emp1._Emploree__salary) print(emp1.salary) #可以直接调用 emp1.salary=10 #报错 emp1.salary=20000 #设置新的值 print(emp1.salary) 结果 2000 2000 错误,重新输入 20000