Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Lære Method super() | Inheritance
Object-Oriented Programming in Python

book
Method super()

To call the parent's class method instead of the current one, we use the_super()_method in Python.

Code

We create the Cat object. The super() method inside the Cat object refers to the parent's class Animal. So Animal constructor is called first.

Afterward, go back to the Cat constructor, initialize the age attribute and print the message.

class Animal:
def __init__(self, name):
print('Calling Animal constructor')
self.name = name

class Cat(Animal):
def __init__(self, name, age):
super().__init__(name)
self.age = age
print('Calling Cat constructor')

cat = Cat('Archie', 12)
123456789101112
class Animal: def __init__(self, name): print('Calling Animal constructor') self.name = name class Cat(Animal): def __init__(self, name, age): super().__init__(name) self.age = age print('Calling Cat constructor') cat = Cat('Archie', 12)
copy
question mark

The last output is:

class Parent:
def __init__(self):
print('Parent constructor')
class Child(Parent):
def __init__(self):
super().__init__()
print('Child constructor')
print('The end')

child = Child()

Select the correct answer

Alt var klart?

Hvordan kan vi forbedre det?

Takk for tilbakemeldingene dine!

Seksjon 3. Kapittel 3

Spør AI

expand
ChatGPT

Spør om hva du vil, eller prøv ett av de foreslåtte spørsmålene for å starte chatten vår

some-alt