property在python2和python3中的區別

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

公司原來的python2的代碼python

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的時候報錯code

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的文檔實例裏面都不是這麼寫的,因此爲了簡便和不出錯,咱們統一使用下面的這種寫法ip

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):開發

相關文章
相關標籤/搜索