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 ourMyUpperStrto use the__init__method of its parent class.
Tests #
MyStr("It's time to code!").textshould 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!").textshould be"IT'S TIME TO CODE!"print(MyUpperStr("It's time to code!"))should print out the message"IT'S TIME TO CODE!"
Getting Started with Python
Data Types
Python Functions
Statements in Python
Basic Debugging in Python
Basic Algorithm
Object-Oriented Programming
Error Handling
Intermediate Algorithm
Python Modules