我正在尝试从 name
派生 id_
的默认值,反之亦然。
@dataclass
class Item:
id_ = NAME_TO_ID[name]
name = ID_TO_NAME[id_]
我应该能够像这样调用该类:
Item(id_=123)
Item(name='foo')
如果可能的话,我还希望该类在提供 id_
和 name
时引发错误。
Item(id_=123, name='foo') # ValueError: id_ and name cannot be provided together
关于我应该如何去做这件事有什么建议吗?
最佳答案
您可以使用写 __post_init__
进行这些验证的方法
from dataclasses import dataclass, field
@dataclass
class Item:
id_: int = field(default=None)
name: str = field(default=None)
def __post_init__(self):
if self.id_ is None and self.name is None:
raise TypeError("You must provide exactly one of name or id_")
if self.id_ is not None and self.name is not None:
raise TypeError("You must provide exactly one of name or id_")
if self.id_ is not None:
self.name = id_to_name(self.id_)
else:
self.id_ = name_to_id(self.name)
关于python - 如何访问 python 数据类中默认参数中的另一个参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52837669/