我的问题很简单:如何添加属性和setter到classmethod?如何在classmethod上应用属性?
这里是我的代码:
class Ingredient():
__max_stock = 100
__stock = 0
__prix = 0
def __init__(self):
pass
@classmethod
@property
def prix(cls):
return cls.__prix
@classmethod
@prix.setter
def prix(cls, value):
assert isinstance(value, int) and int(abs(value)) == value
cls.__prix = value
Ingredient.prix = 10 #should be OK
Ingredient.prix = 'text' #should raise an error
Ingredient.prix = 10.5 #should raise an error too
问题是,当该变种是一个类变量的setter不起作用。 这里是我的错误:
AttributeError: 'classmethod' object has no attribute 'setter'
我使用Python 3.x的
它是否必须是'classmethod'?为什么不只有一个默认值传递给构造函数,您可以在需要时进行更改? –
我不确定'财产'和'classmethod'是否打算*一起工作 – chepner
首先,最重要的是,感谢您对我的代码进行了美化。 其次,我想保持classmethod的原因是价格是所有成分通用的。所以当我想改变价格时,所有的实例都会有一个更新的价格(以及stock和max_stock等) –