【发布时间】:2020-03-04 11:04:35
【问题描述】:
我想限制一个数据类实例的最大数量并知道该实例的索引。这是我想要的行为:
Veget('tomato', 2.4, 5)
Veget('salad', 3.5, 2)
Veget('carot', 1.2, 7)
for Veget in Veget.instances:
print(Veget)
Veget(index=0, name='tomato', price=2.4, quantity=5)
Veget(index=1, name='salad', price=3.5, quantity=2)
Veget(index=2, name='carot', price=1.2, quantity=7)
我尝试了以下方法,它确实处理了创建限制:
from dataclasses import dataclass
MAX_COUNT = 3
class Limited:
instances = []
def __new__(cls, *_):
if len(cls.instances) < MAX_COUNT:
newobj = super().__new__(cls)
cls.instances.append(newobj)
return newobj
else:
raise RuntimeError('Too many instances')
@dataclass
class Veget(Limited):
name: str
price: float
quantity: int
但打印时不会显示索引:
Veget(name='tomato', price=2.4, quantity=5)
Veget(name='salad', price=3.5, quantity=2)
Veget(name='carot', price=1.2, quantity=7)
【问题讨论】:
-
继承并不是一个很好的解决方案,因为从
Limited继承的所有类都将共享相同的实例列表。我认为您想要一个设置各种类变量和新类的__new__方法的元类。 -
附带说明,当您编写泛型用法
__new__时,您应该将两个参数以及关键字参数传递给__init__(例如def__new__(cls, *_, **__))。如果你不这样做,继承类将不能再有关键字参数,这对数据类尤其不利。
标签: python-3.x python-dataclasses