Skip to content Skip to sidebar Skip to footer

Adding Extra Functionality To Parent Class Method Without Changing Its Name

I have two classes one parent and other child. class Parent(object): def __init__(self): #does something def method_parent(self): print 'Parent' class Ch

Solution 1:

You can always call code from the parent using the super() function. It gives a reference to the parent. So, to call parent_method(), you should use super().parent_method().

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

classParentClass: 
    deff(self): 
        print("Hi!"); 

classChildClass(ParentClass): 
    deff(self):
        super().f(); 
        print("Hello!"); 

In python2, you need to call super with extra arguments: super(ChildClass, self). So, the snippet would become:

classParentClass: 
    deff(self): 
        print("Hi!"); 

classChildClass(ParentClass): 
    deff(self):
        super(ChildClass, self).f(); 
        print("Hello!"); 

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

If you already coded in java, it's basically te same behaviour. You can call super wherever you want. In a method, in the init function, ...

There are also other ways to do that but it's less clean. For instance, you can do:

ParentClass.f(self) 

To call the f function of parent class.

Solution 2:

This is what the super function does.

classChild(Parent):def__init__(self):
        super(Child, self).__init__()

    defmethod_parent(self):
        super(Child, self).method_parent()
        print "Child"

In Python 3, you can call super without the arguments, like super().method_parent()

Solution 3:

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

classChild(Parent):def__init__(self):
        Parent.__init__(self)

    defmethod_parent(self):
        Parent.method_parent(self)  # call method on Parent
        print "Child"

This one is when you want to explicitely name the parent class. If you prefere, you can ask python to give you next class in Method Resolution Order by using super:

defmethod_parent(self):
        super(Child, self).method_parent()  # call method on Parentprint"Child"

Post a Comment for "Adding Extra Functionality To Parent Class Method Without Changing Its Name"