CodeBlanks Logo Icon CodeBlanks

super()

Learn to call the parent with super().

The super() function

super() is a function that gives access to parent class methods. It is mostly used inside __init__ to call the parent's constructor.

Example: class Dog(Animal):\n def __init__(self, name):\n super().__init__(name). Here super().__init__(name) calls the parent's __init__ method and passes name. This way the parent's setup is not rewritten; it is only called.

The super().__init__ pattern

When a child class defines an __init__ method, the parent's __init__ is not called automatically. To set up parent attributes too, you call super().__init__(...) explicitly.

Example: class Dog(Animal):\n def __init__(self, name, breed):\n super().__init__(name)\n self.breed = breed. Here name is for the parent, breed is specific to the child. This pattern sets up both parent and child attributes from one place.

Practice Call super in Dog __init__

First define the Animal class; add def __init__(self, species): and in the body write self.species = species. Then define class Dog(Animal):; add def __init__(self, name):, and in the body write super().__init__("dog") and self.name = name. Then create an instance with d = Dog("Rex") and write print(d.name).

Starter code

main.py
# Define the Animal and Dog classes

Sample solution

main.py
# Define the Animal and Dog classes
class Animal:
    def __init__(self, species):
        self.species = species

class Dog(Animal):
    def __init__(self, name):
        super().__init__("dog")
        self.name = name

d = Dog("Rex")
print(d.name)

Expected output

Rex

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Complete the super call

Question
class Dog(Animal):
    def __init__(self, name):
        ____().__init__(name)
Answer
class Dog(Animal):
    def __init__(self, name):
        super().__init__(name)

Explanation: super() gives access to parent methods.

2 What does super() return?

  • The child class instance
  • A new class definition
  • The class name as a string
  • A temporary proxy of the parent class Correct answer

Explanation: super() returns a temporary proxy that gives access to parent methods.

3 Match the super concepts

Term Meaning
super() Parent access
.__init__(name) Parent constructor
self.breed = breed Child attribute

All lessons in Intermediate