Luca
Luca

Reputation: 10996

Can I ensure that python base class method is always called

I have a python abstract base class as follows:

class Node(object):
    """
    All concrete node classes should inherit from this
    """
    __metaclass__ = ABCMeta

    def __init__(self, name):
        self.name = name
        self.inputs = dict()

    def add_input(self, key, value=None, d=None):
        self.inputs[key] = (d, value)

    def bind_input(self):
        print "Binding inputs"

    @abstractmethod
    def run(self):
        pass

Now, various derived classes will inherit from this node class and override the run method. It is always the case that bind_input() must be the first thing that should be called in the run method. Currently, for all derived classes the developer has to make sure to first call self.bind_input(). This is not a huge problem per se but out of curiosity is it possible to ensure this somehow from the base class itself that bind_input is called before executing the child object's run?

Upvotes: 4

Views: 972

Answers (1)

salezica
salezica

Reputation: 77029

The usual object-oriented approach is this:

def run(self):
    self.bind_input()
    return self.do_run()

@abstractmethod
def do_run(self):
    pass # override this method

Have your subclasses override the inner method, instead of the outer one.

Upvotes: 5

Related Questions