How do you use super() in Python?

Asked 2 years ago, Updated 2 years ago, 104 views

In Perl and Java, super() was used to call the method of the parent class.

package Foo;

sub frotz {
    return "Bamf";
}

package Bar;
@ISA = qw(Foo);

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

I don't know how to use it in Python. Can't I access parent classes in Python?

class python inheritance object

2022-09-22 22:23

1 Answers

Python is accessible to parent classes as super() only in the new-style class.

For example,

class Foo: #new-style in python3 and old-style in python2
    def printFoo(self):
        print("Foo!")

class Bar(Foo):
    def __init__(self):
        super(Bar, self).printFoo()

myBar = Bar()

The code for is

Python 3 prints "Foo" An error occurs on python2.


2022-09-22 22:23

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.