![](/img/trans.png)
[英]How to call a method of base class with same name method in derived class in 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成为新式类。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.