property在python2和py

  • 問題背景: 源於公司的原來的程式碼是python2開發的,後來改為python3開發,設計到的property的用法有點不一樣
  • 直接上程式碼

公司原來的python2的程式碼

class LineItem:        def __init__(self, description, weight, price):          self.description = description          self.__weight = weight          self.price = price        @property      def weight(self):          return self.__weight        @weight.setter      def set_weight(self, value):          if value > 0:              self.__weight = value          else:              raise ValueError('weight must be > 0')

運行程式碼

In [2]: l = LineItem('a', 3, 6)    In [3]: l.weight  Out[3]: 3    In [4]: l.weight = 5    In [5]: l.weight  Out[5]: 5

這個程式碼在python2下面執行沒有問題,但是在python3下面執行,會報錯,在執行In [4]: l.weight = 5的時候報錯

In [4]: l.weight = 5  ---------------------------------------------------------------------------  AttributeError                            Traceback (most recent call last)  <ipython-input-4-3c1df6104a5e> in <module>  ----> 1 l.weight = 5    AttributeError: can't set attribute
  • 解決方法

按理說,上面的那種寫法不是很規範,無論是在python2還是python3的文檔實例裡面都不是這麼寫的,所以為了簡便和不出錯,我們統一使用下面的這種寫法

class LineItem:        def __init__(self, description, weight, price):          self.description = description          self.__weight = weight          self.price = price        @property      def weight(self):          return self.__weight        @weight.setter      def weight(self, value):          if value > 0:              self.__weight = value          else:              raise ValueError('weight must be > 0')

主要區別在於這一行def weight(self, value):