Call the method of the parent class from the child class?

When creating a simple object hierarchy in Python, I want to be able to invoke the method of the parent class from the derived class. In Perl and Java, there is a keyword for this( super ) In Perl, I can do this:

package Foo;

sub frotz {
    return "Bamf";
}

package Bar;
@ISA = qw(Foo);

sub frotz {
   my $str = SUPER::frotz();
   return uc($str);
}

In Python, it seems necessary to explicitly name the parent class from the child class. In the above example, I had to perform something like Foo::frotz().

This doesn't seem right, because this behavior makes it difficult to create deep structures. If children need to know which class defines an inherited method, it will cause a variety of information pain.

Is this a real limitation in python, a gap in my understanding, or both?

#1 building

This is an example of using super():

#New-style classes inherit from object, or from another new-style class
class Dog(object):

    name = ''
    moves = []

    def __init__(self, name):
        self.name = name

    def moves_setup(self):
        self.moves.append('walk')
        self.moves.append('run')

    def get_moves(self):
        return self.moves

class Superdog(Dog):

    #Let's try to append new fly ability to our Superdog
    def moves_setup(self):
        #Set default moves by calling method of parent class
        super(Superdog, self).moves_setup()
        self.moves.append('fly')

dog = Superdog('Freddy')
print dog.name # Freddy
dog.moves_setup()
print dog.get_moves() # ['walk', 'run', 'fly']. 
#As you can see our Superdog has all moves defined in the base Dog class

#2 building

There is also a super () in python.

An example of calling a superclass method from a subclass method

class Dog(object):
    name = ''
    moves = []

    def __init__(self, name):
        self.name = name

    def moves_setup(self,x):
        self.moves.append('walk')
        self.moves.append('run')
        self.moves.append(x)
    def get_moves(self):
        return self.moves

class Superdog(Dog):

    #Let's try to append new fly ability to our Superdog
    def moves_setup(self):
        #Set default moves by calling method of parent class
        super().moves_setup("hello world")
        self.moves.append('fly')
dog = Superdog('Freddy')
print (dog.name)
dog.moves_setup()
print (dog.get_moves()) 

This example is similar to the example explained above, but super does not pass any parameters, but the above code is executable in Python version 3.4.

#3 building

If you don't know how many parameters you might get, and you also want to pass them all to the child:

class Foo(bar)
    def baz(self, arg, *args, **kwargs):
        # ... Do your thing
        return super(Foo, self).baz(arg, *args, **kwargs)

(from: Python - the cleanest way to override \\\\\\\\\\? )

#4 building

Python 3 has a different and simpler syntax for calling the parent method.

If the Foo class inherits from Bar, you can call Bar. Init from Foo through super()

class Foo(Bar):

    def __init__(self, *args, **kwargs):
        # invoke Bar.__init__
        super().__init__(*args, **kwargs)

#5 building

In Python 2, I'm not very happy with super(). I used jimifiki's answer on this SO thread, How to reference the parent method in python? . Then I added my own tips, which I think are usability improvements (especially if your class name is long).

Define the base class in a module:

 # myA.py

class A():     
    def foo( self ):
        print "foo"

Then import the class as parent level into another module:

# myB.py

from myA import A as parent

class B( parent ):
    def foo( self ):
        parent.foo( self )   # calls 'A.foo()'

Tags: Python Java

Posted on Fri, 10 Jan 2020 08:09:12 -0500 by bschaeffer