Super() function for calling superclass methods
Hey there, young Python enthusiasts! Today, we’re diving into a super cool topic in Python programming called the super() function. Don’t worry if it sounds a bit tricky at first. By the end of this course, you’ll be a super super() expert!
What is the Super() Function? Imagine you have a superhero, let’s call him “Superman.” Now, Superman is super strong, super fast, and super smart, right? But what if Superman also had a mentor who taught him everything he knows? That mentor is like a superclass, and Superman is like a subclass. The super() function helps our subclass (Superman) call upon the powers and wisdom of its superclass (mentor).
Syntax of the Super() Function: In Python, using the super() function is as easy as pie! Here’s how it looks:
class Subclass(Superclass):
def __init__(self):
super().__init__()
# more code here
Here, Subclass is our superhero (subclass), and Superclass is the mentor (superclass). By using super().__init__(), our subclass can call the __init__() method of its superclass.
Let’s break down the syntax:
super()– This is the function that creates a connection between the subclass and its superclass.__init__()– This is the method we want to call from the superclass. It’s like asking the mentor for guidance when our superhero is created.
Python Code Examples:
- Simple Inheritance Example:
class Animal:
def make_sound(self):
print("Some generic sound")
class Dog(Animal):
def make_sound(self):
super().make_sound()
print("Woof!")
# Creating an instance of Dog
dog = Dog()
dog.make_sound()
- Using Super() with Multiple Inheritance:
class A:
def say_hello(self):
print("Hello from class A")
class B(A):
def say_hello(self):
print("Hello from class B")
class C(A):
def say_hello(self):
print("Hello from class C")
class D(B, C):
def say_hello(self):
super().say_hello()
# Creating an instance of D
d = D()
d.say_hello()
Practice Questions:
- Create a class called
Personwith a methodgreet()that prints “Hello, I am a person!”. Then create a subclassStudentthat overrides thegreet()method to print “Hello, I am a student!” using thesuper()function. - Define a class
Shapewith a methodarea()that returns 0. Create a subclass calledSquarethat overrides thearea()method to return the area of a square with a side length of 5 using thesuper()function.
Solutions:
class Person:
def greet(self):
print("Hello, I am a person!")
class Student(Person):
def greet(self):
super().greet()
print("Hello, I am a student!")
# Creating an instance of Student
student = Student()
student.greet()
class Shape:
def area(self):
return 0
class Square(Shape):
def area(self):
return super().area() + 5 * 5
# Creating an instance of Square
square = Square()
print("Area of the square:", square.area())
Now, go ahead and try these examples and practice questions to become a super() Python programmer!
Keep coding and stay super! 🚀
