Adding additional functionality to the method of the parent class without changing its name

I have two classes: one parent and another child.

class Parent(object): def __init__(self): #does something def method_parent(self): print "Parent" class Child(Parent): def __init__(self): Parent.__init__(self) def method_parent(self): print "Child" 

After parent inheritance, I want to change the parent method method_parent , preserving the original functionality of this method and adding additional lines of code to this method.

I know that I can create a new method, for example

 def method_child(self): self.method_parent() #Add extra lines of code to perform something 

But I want to use the original method name. I can not copy the source for this method, because the method from the C module

what I want to achieve is something like this

 def method_parent(): #do parent_method stuff #do extra stuff 

Is it possible?

+6
source share
3 answers

You can always call the code on the parent using the super() function . He gives a link to the parent. So, to call parent_method() , you must use super().parent_method() .

Here is a code snippet (for python3) that shows how to use it.

 class ParentClass: def f(self): print("Hi!"); class ChildClass(ParentClass): def f(self): super().f(); print("Hello!"); 

In python2, you need to call super with additional arguments: super(ChildClass, self) . Thus, the fragment will be as follows:

 class ParentClass: def f(self): print("Hi!"); class ChildClass(ParentClass): def f(self): super(ChildClass, self).f(); print("Hello!"); 

If you call f() on an instance of ChildClass, it will show: "Hello! Hello!".

If you are already encoded in java, this is basically the same behavior. You can call super wherever you want. In the method, in the function init, ...

There are other ways to do this , but it is less clean . For example, you can:

 ParentClass.f(self) 

Calling the function f of the parent class.

+6
source

This is what the super function does.

 class Child(Parent): def __init__(self): super(Child, self).__init__() def method_parent(self): super(Child, self).method_parent() print "Child" 

In Python 3, you can call super without arguments, such as super().method_parent()

+4
source

You can call the parent method exactly the same as you used for __init__ one:

 class Child(Parent): def __init__(self): Parent.__init__(self) def method_parent(self): Parent.method_parent(self) # call method on Parent print "Child" 

This is the one when you want to explicitly specify the parent class. If you prefer, you can ask python to give you the following class in the Order Resolution Resolution with super :

  def method_parent(self): super(Child, self).method_parent() # call method on Parent print "Child" 
+1
source

All Articles