Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (1.6k points)

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

package Boo;

sub frotz {

    return "Bamf";

}

package Bar;

@ISA = qw(Boo);

sub frotz {

   my $str = SUPER::frotz();

   return uc($str);

}

In python, it appears that I have to name the parent class explicitly from the child. In the example above, I'd have to do something like Boo::frotz().

This doesn't seem right, since this behavior makes it hard to make deep hierarchies. If children need to know what class defined an inherited method, then all sorts of information pain is created.

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

1 Answer

0 votes
by (119k points)

You can use the following code using super() in Python to call the parent class from child class:

class Foo(Bar):

    def baz(self, arg):

        return super().baz(arg)

For Python versions < 3.0, use the following python code to call parent method:

 class Foo(Bar):

    def baz(self, arg):

        return super(Foo, self).baz(arg)

If you want to learn Python then take up this Python Certification course that provides instructor-led training, certification, and also job assistance

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
0 votes
4 answers

Browse Categories

...