property在python2和python3中的区别

3次阅读

共计 1107 个字符,预计需要花费 3 分钟才能阅读完成。

  • 问题背景: 源于公司的原来的代码是 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):

正文完
 0