- 问题背景: 源于公司的原来的代码是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')
PYthon学习企鹅裙:88198-2657 领取python自动化编程资料教程
运行代码
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
的时候报错