[关闭]
@runzhliu 2018-02-22T01:41:00.000000Z 字数 536 阅读 689

Python 中的 property

Python property


参考资料
Effective Python


在面向对象的编程语言中,经常需要在类中定义各种属性的获取器和设置器。以下代码是利用 Python 实现的具有获取和设置器的类。

  1. class OldResistor(object):
  2. def __init__(self, ohms):
  3. self.__ohms = ohms
  4. def get_ohms(self):
  5. return self.__ohms
  6. def set_ohms(self, ohms):
  7. self.__ohms = ohms
  8. if __name__ == '__main__':
  9. r0 = OldResistor(50e3)
  10. print "Before: %5r", r0.get_ohms()
  11. r0.set_ohms(10e3)
  12. print "After: %5r", r0.get_ohms()
  13. r0.set_ohms(r0.get_ohms() + 5e3)
  14. print "SelfAdd: %5r", r0.get_ohms()

可以看到获取器和设置器会有个问题,就是做类似自增的操作的时候会非常不便利。而对于 Python 本身而言,基本上是不需要手工实现这些方法的,而是应该从简单的 public 属性开始写起。

添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注