一、用属性取代get和set方法
常规的get和set方法如下:
class OldResistor(): def __init__(self, ohms): self.__ohms = ohms def get_ohms(self): return self.__ohms def set_ohms(self, ohms): self.__ohms = ohms if __name__ == '__main__': r0 = OldResistor(50e3) print(r0.get_ohms()) r0.set_ohms(10e3) print(r0.get_ohms())
@property装饰器getter,和setter方法协同工作
class Resistor(): def __init__(self, ohms): self.ohms = ohms self.voltage = 0 self.current = 0 class VolResistor(Resistor): def __init__(self, ohms): super().__init__(ohms) # 继承父类的变量 self.__vol = 100 # __开头的变量为内部变量,无法在外部引用 @property # getter设置voltage属性 def voltage(self): return self.__vol @voltage.setter def voltage(self, voltage): self.__vol = voltage self.current = self.__vol / self.ohms if __name__ == '__main__': r1 = Resistor(50e3) r1.ohms = 10e3 # public属性 r1.ohms += 5e3 print(r1.ohms) r2 = VolResistor(10) print(r2.voltage) # getter属性,不会执行voltage的setter方法,不会更新current属性 print(r2.current) r2.voltage = 100 # voltage属性赋值时,将会执行voltage的setter方法,更新current属性 print(r2.current)
二、考虑用@property来代替属性重构
pass
三、用描述符来改写需要服用的@property方法
__get__ __set__
四、__getattr__、__getattribute__、__setattr__实现按需生成的属性
pass
五、元类
__new__
pass