在实例化之前验证 init 参数而不覆盖内置 init 数据类的 pythonic 方法是什么?
我想也许可以利用 __new__
dunder-method 合适吗?
from dataclasses import dataclass
@dataclass
class MyClass:
is_good: bool = False
is_bad: bool = False
def __new__(cls, *args, **kwargs):
instance: cls = super(MyClass, cls).__new__(cls, *args, **kwargs)
if instance.is_good:
assert not instance.is_bad
return instance
最佳答案
定义a __post_init__
method on the class ;如果定义的话,生成的 __init__ 将调用它:
from dataclasses import dataclass
@dataclass
class MyClass:
is_good: bool = False
is_bad: bool = False
def __post_init__(self):
if self.is_good:
assert not self.is_bad
这甚至在 the replace
function 时也有效。用于创建一个新实例。
关于Python数据类,验证初始化参数的Python式方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60179799/