【问题标题】:How do I call a base class method from within the same overloaded derived class method in python?如何从 python 中相同的重载派生类方法中调用基类方法?
【发布时间】:2014-01-14 07:26:56
【问题描述】:

我的 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

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

Traceback(最近一次调用最后一次):文件“stdin”,第 1 行,in 文件“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() must be 以 MicroSim 实例作为第一个参数调用(获取 int 实例 而是)

我已尝试在此处搜索此类问题,并找到了类似的帖子,并尝试了那里讨论的所有解决方案,但此错误似乎并没有消失。我已尝试将有问题的行更改为,

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

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

【问题讨论】:

  • 您需要使用class MicroSim(object) 使MicroSim 成为一个新型类。
  • ThresholdCollabSim._generate_file_name(self, curr_run) 呢?
  • ThresholdCollabSim._generate_file_name(self, curr_run) 没有帮助。什么是新式类?
  • 使 MicroSim 成为一种新型的类有效。谢谢!

标签: python python-2.7


【解决方案1】:

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

【讨论】:

  • 我在写出问题时缺少“自我”错字,已修复。但它并没有解决问题。什么是新式类?
【解决方案2】:

作为补充。

您在旧式类中使用super

super 文档中,我们知道:

super() 仅适用于新式类。

一个新式的类是

任何继承自对象的类。

【讨论】:

    猜你喜欢
    • 2013-03-23
    • 1970-01-01
    • 2021-07-18
    • 1970-01-01
    • 2014-03-17
    • 1970-01-01
    • 1970-01-01
    • 2023-03-12
    • 1970-01-01
    相关资源
    最近更新 更多