我想限制数据类实例的最大数量并了解实例的索引。这是我想要的行为:
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)
最佳答案
对数据类进行隐式限制或要求某种验证通常是通过指定的__post_init__
来实现的。而不是使用对象继承。利用它的实现可能如下所示,在我看来,这更容易维护和理解:
from dataclasses import dataclass, field
MAX_COUNT = 3
VEGET_INDEX = []
@dataclass
class Veget:
index: int = field(init=False)
name: str
price: float
quantity: int
def __post_init__(self):
self.index = len(VEGET_INDEX)
if self.index >= MAX_COUNT:
raise RuntimeError("Too many instances")
VEGET_INDEX.append(self)
您还可以使用计数器代替在初始化后例程中递增的列表,但引用列表似乎对于调试目的很方便。无论如何,创建三个允许的实例并尝试创建第四个实例将如下所示:
>>> Veget('tomato', 2.4, 5)
Veget(index=0, name='tomato', price=2.4, quantity=5)
>>> Veget('salad', 3.5, 2)
Veget(index=1, name='salad', price=3.5, quantity=2)
>>> Veget('carot', 1.2, 7)
Veget(index=2, name='carot', price=1.2, quantity=7)
>>> Veget('potato', 0.7, 3)
Traceback (most recent call last):
File "<input>", line 1, in <module>
File "<string>", line 5, in __init__
File "<input>", line 17, in __post_init__
RuntimeError: Too many instances
关于python-3.x - 如何获取python3数据类实例的索引?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58755974/