Anshul
Anshul

Reputation: 73

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

I have the following classes setup in my python project,

In 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)

In 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!

In 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

When I run this code I get the error msg,

Traceback (most recent call last): File "stdin", line 1, in File "H:...\MicroSimRunner.py", line 11, in run_sims thresholdSim.run() File "H:...\MicroSim.py", line 42, in run self._generate_file_name(r) File "H:...\ThresholdCollabSim.py", line 17, in _generate_file_name super(ThresholdCollabSim, self)._generate_file_name(curr_run) TypeError: unbound method _generate_file_name() must be called with MicroSim instance as first argument (got int instance instead)

I have tried searching for issues like this here and have found similar posts and have tried all the solutions discussed there but this error doesn't seem to go away. I have tried changing the line in question to,

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

but it changes nothing (same error). I am relatively new at Python programming so this may just be a silly mistake. Any help is much appreciated. Thanks!

Upvotes: 0

Views: 71

Answers (2)

flyer
flyer

Reputation: 9846

As a supplement.

You use super in the old-style class.

From the super documentation, we know that:

super() only works for new-style classes.

And a new-style class is

Any class which inherits from object.

Upvotes: 1

BrenBarn
BrenBarn

Reputation: 251618

You forgot the self argument in your derived _generate_file_name method. Also, you need to make MicroSim a new-style class by using class MicroSim(object).

Upvotes: 1

Related Questions