内容简介:公司原来的python2的代码运行代码这个代码在python2下面执行没有问题,但是在python3下面执行,会报错,在执行
- 问题背景: 源于公司的原来的代码是 python 2开发的,后来改为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):
以上所述就是小编给大家介绍的《property在python2和python3中的区别》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!
猜你喜欢:本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
白话机器学习算法
[新加坡] 黄莉婷、[新加坡] 苏川集 / 武传海 / 人民邮电出版社 / 2019-2 / 49.00元
与使用数学语言或计算机编程语言讲解算法的书不同,本书另辟蹊径,用通俗易懂的人类语言以及大量有趣的示例和插图讲解10多种前沿的机器学习算法。内容涵盖k均值聚类、主成分分析、关联规则、社会网络分析等无监督学习算法,以及回归分析、k最近邻、支持向量机、决策树、随机森林、神经网络等监督学习算法,并概述强化学习算法的思想。任何对机器学习和数据科学怀有好奇心的人都可以通过本书构建知识体系。一起来看看 《白话机器学习算法》 这本书的介绍吧!