5

I'm new with python and having some trouble regarding inheritance.

i have this class:

class A(object):
    def __init__(self, foo, bar):
        pass     
    def func1(self):
        op1()
        op2()
    def func2(self):
        pass

I'm using another class that is overriding it :

class B(A):
    def func2(self):
        # do something

the problem is that I want to get func1 with all its operations and add for example op3() so that when using this class I will have the option to use op1, op2 or op3.

I've tried using:

def func1(self):
    op3()

but it just gave me the option of op3 without op1 and op2.

I saw that there is "super" option but I'm not sure I understand how to use it.

1
  • 3
    Also, you need to have __init__, not _init_. Commented Dec 5, 2013 at 15:03

1 Answer 1

9

You can call the super-class implementation in func1:

class B(A):
    def func1(self):
        super(B, self).func1()
        op3()

Here super(B, self).func1 will search the class hierarchy in MRO (method resolution order), from class B onwards for the next func1() method, bind it to self and let you call it.

This will invoke the original func1() first, executing op1() and op2(), and your overridden version can then add new operations to follow.

You could also call op3() first, then invoke the base implementation.

You can also look up the parent method directly on class A, but that method will then be unbound. Pass in self explicitly:

class B(A):
    def func1(self):
        A.func1(self)
        op3()

This bypasses searching the class inheritance hierarchy making your class less flexible.

See Raymond Hettinger's blog post on super() for some excellent practical advice on when to use super().

Sign up to request clarification or add additional context in comments.

13 Comments

Or also A.func1(self), no?
@qwertynl: Yes, but that'd be a non-cooperative invocation. Using super() you can add another version of func1() into the mix too.
@qwertynl In such an easy case, yes. But with a class B(A,C,F,G):, these parent classes having similiar dependencies, it gets more complicated.
so is there a difference between A.func1(self) and super(B,self)?
@user1386966: Not until you start mixing in more base classes, or create more complicated structures. The thing is, production code has this habit of evolving and becoming more complex over time.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.