Python3-2020-测试开发-20- Python中装饰器@property
装饰器
为私有属性提供getter和setter方法
原始实现代码:
class Employee01: def __init__(self,name,age): self.__name = name self.__age = age def get_age(self): return self.__age def set_age(self,age): if 1 < age <200: self.__age = age else: print("年龄不符合规则") @property def salary(self): print("salary run ...") return 10 e = Employee01("chu01",18) # e.salary() print(e.salary) """ salary run ... 10 """ e.set_age(100) print(e.get_age()) # 100
使用装饰器优化代码
class Employee02: def __init__(self,name,age): self.__name = name self.__age = age @property def age(self): return self.__age @age.setter def age(self,age): if 1 < age <=200: self.__age = age else: print("年龄不符合规则") e2 = Employee02("chu02",200) # e2.age = -200 # 年龄不符合规则 e2.age = 200 print(e2.age) # 200
相关推荐
FlySky 2020-10-16
FlySky 2020-09-29
bizercsdn 2020-09-17
python0 2020-08-16
chenzulong 2020-08-16
LULUBAO 2020-07-08
一叶不知秋 2020-06-28
yogoma 2020-06-14
周小董 2020-06-10
xmwang0 2020-06-08
JJandYY 2020-05-31
Andrewjdw 2020-05-27
wklken的笔记 2020-05-27
zhuquan0 2020-05-26
chongtianfeiyu 2020-05-20
cas的无名 2020-05-19
qianjq 2020-05-10
小方哥哥 2020-05-05