首页 > 解决方案 > 超类 __init__ 覆盖子类构造函数

问题描述

我正在与 cantera 合作,试图cantera.Solution通过创建 subclass 来创建类的扩展Flow。这基本上是用它的运动参数来扩展对气相的描述。

Solution是通过使用某些构造的**kwargs。我想要做的是将它们保存**kwargs在一个Template类对象中并使用该对象来定义我Flow的对象。我试图Solution.__init__使用. Flow.__init___ 但是,似乎覆盖了.Templatesuper()Solution.__init__Flow.__init__

class Flow(Solution):

  def __init__(self, template, velocity):

    super().__init__(species = template.species,
                     reactions = template.reactions, 
                     thermo = template.thermo, 
                     kinetics = 'GasKinetics')

    self.velocity = velocity

现在,假设我有一个Template名为 的适当对象template,它用作所有**kwargs所需对象的容器Solution.__init__。我正在尝试创建我的Flow对象:

flow = Flow(template, 230)

我得到:

AttributeError: 'Template' object has no attribute 'encode'

如果我尝试,我会得到同样的错误:

S = Solution(template, 230)

所以基本上我所有的子类构造函数参数都传递给超类的构造函数。由于未覆盖超类构造函数,因此我不能使用Template对象将 my 定义SolutionFlow. 我在网上读到这不是默认行为,因为子类构造函数应该覆盖超类构造函数。这有什么帮助?

标签: pythonpython-3.xinitshadowingcantera

解决方案


我找到了解决方案。事实证明,Cantera 是基于 cython 的。实际上, Solution 类包含init,但 Python 并未将其视为函数,而是将其视为插槽包装器。因此,子类无法使用自己的构造函数来隐藏init 。我已经使用我的代码中未提及的内容优雅地处理了这个问题。


推荐阅读