参考代码:
1 from functools import partial 2 3 class Property: # 数据描述符 4 def __init__(self, fget=None, fset=None): 5 self.fget = fget 6 self.fset = fset 7 8 def __get__(self, instance, owner): 9 return partial(self.fget, instance)() 10 11 def __set__(self, instance, value): 12 # instance._data = value # 修改了保护变量 13 self.fset(instance, value) 14 15 def setter(self, fn): 16 self.fset = fn 17 return self 18 class A: 19 def __init__(self, data): 20 self._data = data # 实例化的时候,保护属性直接注入 21 22 @Property # data = Property(data) 23 def data(self): 24 return self._data 25 26 @data.setter # data = data.setter(data)= Property(data) 27 def data(self, value): 28 self._data = value 29 30 a = A(9) 31 print(a.__dict__) # {'_data': 9} 32 33 print(a.data) # 是一个数字 34 35 a.data = 8 36 print(a.__dict__) 37 print(a.data) # 是一个数字 38 39 a.data = 0 40 print(a.__dict__) 41 print(a.data) # 是一个数字