how to call parent class methods in python?

11,090

Solution 1

Use super(ClassName, self)

class my_class(object):
    def __init__(self):
    # build my objects 
    def foo(self,*args,**kwargs):
    # do something with them

class my_extended_class(my_class):
    def foo(self,*args,**kwargs):
        super(my_extended_class, self).foo(*args,**kwargs)
        # other child-specific statements
        return self

Compatibility is discussed in How can I call super() so it's compatible in 2 and 3? but in a nutshell, Python 3 supports calling super with or without args while Python 2 requires them.

Solution 2

You can use the super() method. For example:

class my_extended_class(my_class):
   def foo(self,*args,**kwargs):
      #Do your magic here 
      return super(my_extended_class, self).foo(self,*args,**kwargs)

You might go to this link and find other answers as well.

Call a parent class's method from child class in Python?

Share:
11,090
00__00__00
Author by

00__00__00

Updated on June 04, 2022

Comments

  • 00__00__00
    00__00__00 almost 2 years

    I am writing a class in python.

    class my_class(object):
        def __init__(self):
        # build my objects 
        def foo(self,*args,**kwargs):
        # do something with them
    

    Then I would like to extend this class:

    class my_extended_class(my_class):
    

    But I can not figure out what is the correct way of accessing parent methods.

    Shall I:

    1) create an instance of a father object? at constructor time

    def __init__(self):
        self.my_father=my_class()
        # other child-specific statements
        return self
    def foo(self,*args,**kwargs):
        self.my_father.foo(*args,**kwargs)
        # other child-specific statements
        return self
    

    2) call father methods 'directly'?

    def foo(self,*args,**kwargs):
        my_class.foo(*args,**kwargs)
        # other child-specific statements
        return self
    

    3) other possible ways?

    • ramganesh
      ramganesh about 6 years
      Use the super() function
    • 00__00__00
      00__00__00 about 6 years
      would that work consistency across python versions 2.6 to 3.5?
    • ramganesh
      ramganesh about 6 years
    • avigil
      avigil about 6 years
      yes, parameters to super are optional in python 3 but if you specify them for python2 compatibility it will work fine