How do I call python subclassed methods from superclass methods?

2.6k Views Asked by At

I have the following kind of superclass / subclass setup:

class SuperClass(object):
    def __init__(self):
        self.do_something() # requires the do_something method always be called

    def do_something(self):
        raise NotImplementedError

class SubClass(SuperClass):
    def __init__(self):
        super(SuperClass, self).__init__() # this should do_something 

    def do_something(self):
        print "hello"

I would like the SuperClass init to always call a not-yet-implemented do_something method. I'm using python 2.7. Perhaps ABC can do this, but it is there another way?

Thanks.

1

There are 1 best solutions below

0
On

Your code is mostly correct, except for the use of super. You need to put the current class name in the super call, so it would be:

super(SubClass, self).__init__()

Since you put in the wrong class name, SuperClass.__init__ wasn't called, and as a result do_something wasn't called either.