- 問題背景: 源于公司的原來的代碼是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)
in
----> 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):
更多文章、技術交流、商務合作、聯系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號聯系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元
