Editor settings

General settings

Save settings

Learn to program with Python

Calling parent class' methods #

The super() function is a built-in function that allows you to access and invoke methods and properties from a parent class within a subclass. super() is often used in the context of inheritance, where a child class inherits from a parent class. By calling super() within a method of the child class, you can refer to the parent class and utilize its methods and properties.

For example:

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

    def greet(self):
        return f"Hello, {self.name}!"

class Child(Parent):
    def __init__(self, name, age):
        super().__init__(name)
        self.age = age

    def greet(self):
        parent_greeting = super().greet()
        return f"{parent_greeting} I'm {self.age} years old."

child = Child("Alice", 10)
print(child.greet())  # Output: Hello, Alice! I'm 10 years old.

In the example above, we have a Parent class with an __init__() method and a greet() method. The Child class inherits from the Parent class.

Within the __init__() method of the Child class, we use super().__init__(name) to call the __init__() method of the parent class and pass the name argument to it. This allows us to initialize the name attribute inherited from the parent class.

Similarly, in the greet() method of the Child class, we use super().greet() to call the greet() method of the parent class and retrieve the parent's greeting. We then extend the greeting by appending the child's age.


Exercise #

  • Define the __init__ method in our MyUpperStr to use the __init__ method of its parent class.

Tests #

  • MyStr("It's time to code!").text should be "It's time to code!"
  • print(MyStr("It's time to code!")) should print out the message "It's time to code!"
  • MyUpperStr("It's time to code!").text should be "IT'S TIME TO CODE!"
  • print(MyUpperStr("It's time to code!")) should print out the message "IT'S TIME TO CODE!"
Output will be displayed here