Python 如何使用类装饰器来拥有只读变量

Python 如何使用类装饰器来拥有只读变量,python,class,oop,decorator,Python,Class,Oop,Decorator,我希望变量next\u id为只读。我有一个提示,它应该使用decorator实现。有什么帮助吗 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

我希望变量
next\u id
为只读。我有一个提示,它应该使用decorator实现。有什么帮助吗

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())

如果我正确理解了您的意思,您希望为
next\u id
赋值一次,然后在代码执行期间不更改它

换句话说,您希望
next\u id
为常数。在python中没有常量这样的东西。您可以重新分配任何您喜欢的变量

然而,python中有一个约定。如果您希望某个变量类似于常量,请使用大写字母命名,不要更改它

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

在Java等其他语言中,您可以使用word
public static final int NEXT\u ID=…
创建一个常量。如果您试图更改
NEXT\u ID
,java编译器会对此抱怨。

NEXT\u ID
设置为只读对于您正在解决的问题没有任何意义,因为您每次创建类的新实例时都会更新它。无论如何,在Python中实现这一点是不可能的。我怀疑您实际上被要求做的是为
产品
提供一个只读属性
id\u no
,该属性返回
\u id no

在末尾将其添加到类定义中(并确保将其缩进,使其实际位于类定义中):

然后你可以这样做:

>>> 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
三星电视=产品('telewizor kolorowy 40 cali',2499.00,5) >>>tv_samsung.id_no 1. >>>tv_samsung.id_no=6 回溯(最近一次呼叫最后一次): 文件“”,第1行,在 tv_samsung.id_no=6 AttributeError:无法设置属性
你所说的
只读是什么意思,那么你打算如何在那里更新它?!就是这样!非常感谢:)
>>> 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