继承cantera.Solution时父类__init__提前调用报错的原因与解决方法
Cantera Solution类继承报错解决方案
问题原因
cantera.Solution是Cython实现的扩展类,Cython扩展类实例化的执行顺序为:先执行父类的__cinit__初始化方法,再执行Python层面定义的__init__方法- 你实例化
SolutionExtended()时没有传入任何参数,父类__cinit__先接收到空参数,直接触发「参数不足无法定义相」的报错,子类__init__中的打印逻辑完全没有执行机会,和你之前的猜想完全吻合。
修复方案
要实现不需要外部显式传入化学模型参数的需求,需要重写子类的__new__方法,将固定的模型参数提前传递给父类的实例化逻辑,修复后的代码如下:
import cantera gas = cantera.Solution('gri30.cti') gas() class SolutionExtended(cantera.Solution): def __new__(cls, *args, **kwargs): # 内部固定传入化学模型文件,不需要外部传参 return super().__new__(cls, "gri30.cti") def __init__(self): print("Beginning of SolutionExtended.__init__") # 父类核心初始化逻辑已在__new__阶段完成,无需重复调用super().__init__ print("End of SolutionExtended.__init__") gas = SolutionExtended() gas()
注意事项
如果你后续需要支持动态传入其他模型文件,也可以在__new__方法中添加参数判断逻辑,灵活适配不同使用场景。
内容的提问来源于stack exchange,提问作者Bryan M
相关产品推荐
相关产品推荐

