00__00__00
00__00__00

Reputation: 5327

how to call parent class methods in python?

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?

Upvotes: 2

Views: 15608

Answers (2)

Daniel Dang
Daniel Dang

Reputation: 31

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?

Upvotes: 3

avigil
avigil

Reputation: 2246

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.

Upvotes: 7

Related Questions