2

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?

4
  • 1
    Use the super() function Commented Mar 30, 2018 at 6:07
  • would that work consistency across python versions 2.6 to 3.5? Commented Mar 30, 2018 at 6:08
  • 1
    Possible duplicate of Call a parent class's method from child class in Python? Commented Mar 30, 2018 at 6:08
  • 1
    yes, parameters to super are optional in python 3 but if you specify them for python2 compatibility it will work fine Commented Mar 30, 2018 at 6:10

2 Answers 2

7

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.

Sign up to request clarification or add additional context in comments.

Comments

3

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?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.