繁体   English   中英

如何从python中相同的重载派生类方法中调用基类方法?

[英]How do I call a base class method from within the same overloaded derived class method in python?

我在python项目中设置了以下类,

在MicroSim.py中

class MicroSim:
    def __init__(self, other_values):
        # init stuff here

    def _generate_file_name(self, integer_value):
        # do some stuff here

    def run(self):
        # do some more stuff
        self._generate_file_name(i)

在ThresholdCollabSim.py中

from MicroSim import MicroSim

class ThresholdCollabSim (MicroSim):
    # no __init__() implmented

    def _generate_file_name(self, integer_value):
        # do stuff here
        super(ThresholdCollabSim, self)._generate_file_name(integer_value) # I'm trying to call MicroSim._generate_file_name() here

    # run() method is not re-implemented in Derived!

在MicroSimRunner.py中

from ThresholdCollabSim import ThresholdCollabSim

def run_sims(values):
    thresholdSim = ThresholdCollabSim(some_values) # I assume since ThresholdCollabSim doesn't have it's own __init__() the MicroSim.__init() will be used here
    thresholdSim.run() # again, the MicroSim.run() method should be called here since ThresholdCollabSim.run() doesn't exist

当我运行此代码时,我收到错误消息,

回溯(最近一次调用最后一次):文件“stdin”,第1行,在文件“H:... \\ MicroSimRunner.py”第11行,在run_sims中为thresholdSim.run()文件“H:... \\ MicroSim。 py“,第42行,在运行self._generate_file_name(r)文件”H:... \\ ThresholdCollabSim.py“,第17行,在_generate_file_name super(ThresholdCollabSim,self)._ generate_file_name(curr_run)TypeError:unbound method _generate_file_name()必须使用MicroSim实例作为第一个参数调用(改为使用int实例)

我已经尝试在这里搜索这样的问题,并找到了类似的帖子,并尝试了所有解决方案,但这个错误似乎没有消失。 我试过更改有问题的线路,

super(ThresholdCollabSim, self)._generate_file_name(self, curr_run)

但它什么都没改变(同样的错误)。 我在Python编程方面相对较新,所以这可能只是一个愚蠢的错误。 任何帮助深表感谢。 谢谢!

您忘记了派生的_generate_file_name方法中的self参数。 此外,您需要使用class MicroSim(object)使MicroSim成为新式类。

作为补充。

你在旧式课堂上使用super

super文档中,我们知道:

super()仅适用于新式类。

而新式的课程则是

任何继承自object的类。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM