Python数据类,验证初始化参数的Python式方法是什么?

标签 python python-3.x python-dataclasses

在实例化之前验证 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/

相关文章:

python - 如何使用 Python OpenCV 将图像裁剪为仅文本部分?

python - SQLAlchemy 的 UnicodeText 列在我的 MySQL 表上给了我一个 str ;不应该是unicode吗?

python - 如何使用vtk在python中绘制鼠标可旋转点云

python - 从 **kwargs 实例化多个对象的 pythonic 方法是什么?

python-3.x - 使用 @dataclass 获取没有变量 fild 的类变量的字典(repr=False)

python - 包含初始化集的数据类?

python - 将没有主键的 CSV 导入现有表

python - 多参数Python映射

python - While 循环仅正确迭代一次

python-3.x - 我应该如何处理 AWS lambda 实现中的 joblib 多处理?