【问题标题】:How to use class decorator to have read only variable如何使用类装饰器拥有只读变量
【发布时间】:2017-11-17 10:39:40
【问题描述】:

我希望变量next_id 是只读的。我有一个提示,它应该使用装饰器来实现。有什么帮助吗?

next_id = 1

class Product:

    def __init__(self, desc, price, quantity):
        global next_id
        self.__idNo = next_id
        next_id += 1
        self.desc = desc
        self.price = price
        self.quantity = quantity

    def get_id(self):
        return self.__idNo

    def get_total_sum(self):
        return self.price * self.quantity

tv_samsung = Product('telewizor kolorowy 40 cali', 2499.00, 5)
print(tv_samsung.get_id())

【问题讨论】:

  • read only 是什么意思,那你要怎么更新呢?!

标签: python class oop decorator


【解决方案1】:

如果我理解正确,您希望给next_id 赋值一次,然后在代码执行期间不更改它。

换句话说,您希望next_id 是一个常数。在 python 中,没有常量这样的东西。您可以重新分配您喜欢的任何变量。

但是,python 中有一个约定。如果你想让某个变量像一个常量,用大写字母命名它,不要改变它。

...
# Don't change it
NEXT_ID = ...
...

在 Java 等其他语言中,您可以使用单词 public static final int NEXT_ID = ... 创建一个常量。如果您尝试更改 NEXT_ID,java 编译器会报错。

【讨论】:

    【解决方案2】:

    将next_id 设为只读对于您正在解决的问题毫无意义,因为您每次创建类的新实例时都会更新它。无论如何,在 Python 中确实不可能做到这一点。我怀疑你实际上被要求做的是给Product一个只读属性id_no,它返回__idNo。

    将此添加到您的类定义的末尾(并确保将其缩进,以便它实际上是在类定义中):

    @property
    def id_no(self):
        return self.__idNo
    

    那么你可以这样做:

    >>> tv_samsung = Product('telewizor kolorowy 40 cali', 2499.00, 5)
    >>> tv_samsung.id_no
    1
    >>> tv_samsung.id_no = 6
    Traceback (most recent call last):
      File "<pyshell#17>", line 1, in <module>
        tv_samsung.id_no = 6
    AttributeError: can't set attribute
    

    【讨论】:

    • 就是这样!非常感谢你:)
    猜你喜欢
    • 2013-02-22
    • 1970-01-01
    • 2020-11-30
    • 2014-08-15
    • 2021-05-24
    • 2019-06-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多