@property解释器

@property解释器可以将一个方法的调用方式变成属性调用,下面是一个简单的案例

1 #测试property最简化使用
2 class Employee:
3     @property
4     def sarlary(self):
5         print('salary run...')
6         return 10000
7 
8 emp1 = Employee()
9 print(emp1.sarlary)

 

 

 1 #property装饰器的用法
 2 class Employee:
 3     def __init__(self,name,salary):
 4         self.__name = name
 5         self.__salary = salary
 6 
 7     def get_salary(self):
 8         return self.__salary
 9 
10     def set_salary(self,salary):
11         if 1000<salary<50000:
12             self.__salary = salary
13         else:
14             print('录入错误!')
15 
16 emp1 = Employee('Xujie',30000)
17 print(emp1.get_salary())
18 emp1.set_salary(-2000)
19 print(emp1.get_salary())