The super() Function
Part of the Object Oriented Programming section of Coddy's Python journey — lesson 18 of 64.
The super() function allows a child class to call methods from its parent class. This lets you extend parent functionality rather than completely replace it.
Here is an example of using super() in the constructor:
class Animal:
def __init__(self, name):
self.name = name
print(f"Animal created: {name}")
class Dog(Animal):
def __init__(self, name, breed):
super().__init__(name) # Call parent's __init__
self.breed = breed
print(f"Dog breed set: {breed}")Create a dog object:
buddy = Dog("Buddy", "Golden Retriever")
print(f"Name: {buddy.name}, Breed: {buddy.breed}")Output:
Animal created: Buddy
Dog breed set: Golden Retriever
Name: Buddy, Breed: Golden RetrieverUse super() to extend parent methods:
class Animal:
def make_sound(self):
print("Generic animal sound")
class Dog(Animal):
def make_sound(self):
super().make_sound() # Call parent's method first
print("Woof!") # Add dog-specific behaviorCall the extended method:
buddy = Dog()
buddy.make_sound()Output:
Generic animal sound
Woof!Without super(), you would lose the parent's functionality:
class Cat(Animal):
def make_sound(self):
print("Meow!") # Only cat sound, parent method ignored
cat = Cat()
cat.make_sound()Output:
Meow!Key Point: Use super() to call parent class methods from child classes. This allows you to extend functionality rather than completely replace it. Common uses include calling parent __init__ methods and extending parent behavior.
Challenge
MediumIn this challenge, you'll implement a Person and Employee class hierarchy using inheritance.
person.py: Contains the Person class with name and age attributesemployee.py: Contains the Employee class that inherits from Persondriver.py: Main file to test your implementation
Each file contains detailed TODO comments to guide you through the implementation.
Cheat sheet
The super() function allows a child class to call methods from its parent class, extending functionality rather than replacing it.
Using super() in constructors:
class Animal:
def __init__(self, name):
self.name = name
class Dog(Animal):
def __init__(self, name, breed):
super().__init__(name) # Call parent's __init__
self.breed = breedUsing super() to extend methods:
class Animal:
def make_sound(self):
print("Generic animal sound")
class Dog(Animal):
def make_sound(self):
super().make_sound() # Call parent's method first
print("Woof!") # Add child-specific behaviorWithout super(): Child methods completely replace parent functionality instead of extending it.
Try it yourself
# TODO: Import the Person class from person.py
# TODO: Import the Employee class from employee.py
def main():
# TODO: Create a Person object with name "Alice" and age 30
person = None
# TODO: Create an Employee object with name "Bob", age 35, and job "Developer"
employee = None
# TODO: Call the introduce() method on the Person object
# Expected output: "Hi, I'm Alice and I'm 30 years old"
# TODO: Print a blank line for spacing - print()
# TODO: Call the introduce() method on the Employee object
# Expected output:
# "Hi, I'm Bob and I'm 35 years old"
# "I work as a Developer"
if __name__ == "__main__":
main()This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Object Oriented Programming
1Fundamentals of OOP
External FilesIntroduction to OOPClasses vs ObjectsThe self ParameterMethodsAttributesConstructor Method (__init__)Recap - Simple Calculator4Inheritance
Basic InheritanceThe super() FunctionMethod OverridingMultiple InheritanceMethod Resolution OrderRecap - Employee Hierarchy7Special Methods
Magic Methods IntroductionOperator OverloadingContainer Magic MethodsRecap - Custom List10Design Patterns Part 1
Intro to design patternSingleton PatternFactory PatternObserver PatternStrategy Pattern2Decorators
Introduction to DecoratorsProperty DecoratorStatic Method DecoratorClass Method Decorator5Polymorphism
Method Overriding RevisitedDuck TypingAbstract Classes and MethodsInterface DesignRecap - Shape Calculator8Advanced OOP Concepts
Composition vs InheritanceMixinsStatic and Class MethodsClass DecoratorsContext Managers3Class Properties
Instance vs Class VariablesProperty DecoratorsPrivate AttributesRecap - Bank Account Manager6Encapsulation
Public, Protected, Private MemAccess ModifiersInformation HidingProperty Decorators AdvancedRecap - Student Records System12Project: Library Management
Project OverviewBook and User Classes