优化大量的property
首先我们要清楚property方法的定义规则:
1、使用@property装饰方法,被装饰的方法变成属性
2、给属性附加setter等特性,也就意味着在给此属性赋值时,会自动触发此方法的执行
1 def expected_type(name, type): 2 storage_name = "_" + name 3 4 @property 5 def prop(self): 6 return getattr(self, storage_name) 7 8 @prop.setter 9 def prop(self, val): 10 if not isinstance(val, type): 11 raise TypeError("{}值类型期待为:{}".format(storage_name, type)) 12 print(">>{}字段,类型校验通过".format(storage_name)) 13 return setattr(self, storage_name, val) 14 15 return prop 16 17 18 class Valley: 19 name = expected_type("姓名", str) 20 age = expected_type("年纪", int) 21 22 def __init__(self): 23 self.name = 'shixiaogu' 24 self.age = 25