Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python inheritance - how to inherit class function?

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.

like image 999
user1386966 Avatar asked Dec 05 '13 15:12

user1386966


1 Answers

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().

like image 57
Martijn Pieters Avatar answered Oct 23 '22 10:10

Martijn Pieters