Python Dataclass继承问题:子类初始化时父类字段未完成初始化
Python Dataclass继承时__post_init__覆盖引发的字段未初始化问题
在Python中,常规类的继承写法能正常运行,但使用dataclass模块实现继承时,会出现子类访问父类未初始化字段的错误。
示例代码
from dataclasses import dataclass, field @dataclass class Parent_Dataclass: a: str = field(init=False) def __post_init__(self): self.a = 'A is initialiazed here.' @dataclass class Child_DataClass(Parent_Dataclass): def __post_init__(self): print(self.a) class Parent: def __init__(self): self.a = 'A is initialiazed here.' class Child(Parent): def __init__(self): super().__init__() print(self.a) c = Child() # Works ! c_dc = Child_DataClass() # Error !
运行输出
A is initialiazed here. Traceback (most recent call last): File "c:\xxx\test_dataclass_inheritance.py", line 25, in <module> c_dc = Child_DataClass() File "<string>", line 3, in __init__ File "c:\xxx\test_dataclass_inheritance.py", line 17, in __post_init__ print(self.a) AttributeError: 'Child_DataClass' object has no attribute 'a'
问题根源
子类的__post_init__方法直接覆盖了父类的同名方法,导致父类中初始化字段a的逻辑没有被执行,子类访问self.a时自然会抛出属性不存在的错误。而常规类的子类__init__中显式调用了super().__init__(),所以父类的初始化逻辑能正常执行。
解决方案
在子类的__post_init__方法中显式调用父类的__post_init__,确保父类的初始化逻辑先执行:
@dataclass class Child_DataClass(Parent_Dataclass): def __post_init__(self): super().__post_init__() # 优先执行父类的初始化逻辑 print(self.a)
修改后再次运行c_dc = Child_DataClass(),就能正常输出A is initialiazed here.,和常规类的运行结果一致。
内容的提问来源于stack exchange,提问作者Oliver Mohr Bonometti
相关产品推荐
相关产品推荐

