前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >property在python2和py

property在python2和py

作者头像
py3study
发布2020-01-02 18:01:23
3060
发布2020-01-02 18:01:23
举报
文章被收录于专栏:python3python3
  • 问题背景: 源于公司的原来的代码是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):

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2019-10-18 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档