In programming, the mechanism of creating a new class by taking over the features of an existing class (blueprint) while adding new features or modifying parts of it is called “Inheritance.” By using inheritance, you avoid writing common code repeatedly, allowing you to create highly maintainable and efficient programs.
This article explains the basic syntax of class inheritance and the role of the super() function, which calls the initialization method of the parent class.
Basic Concepts of Inheritance
- Parent Class (Base Class / Super Class): The class that is the source of inheritance. It holds the basic functionality.
- Child Class (Derived Class / Sub Class): A new class created by inheriting from the parent class. It has the parent’s features while adding its own unique features.
1. Defining the Parent Class
First, we define the basic class that will serve as the source of inheritance. Here, we create a GameCharacter class representing a “character” in an RPG game. It has a name and health points (HP), and the ability to attack.
class GameCharacter:
"""
Basic character class (Parent Class)
"""
def __init__(self, name, hp):
self.name = name
self.hp = hp
def attack(self):
"""Method for normal attack"""
print(f"{self.name} attacks! Dealt damage to the enemy.")
def show_status(self):
"""Method to display status"""
print(f"Name: {self.name} | HP: {self.hp}")
2. Defining the Child Class (Inheritance)
Next, we inherit from this GameCharacter to create a Wizard class representing a magician. To inherit, write (ParentClassName) after the class name. The Wizard has a new attribute called Magic Points (MP) and a new method to cast spells, in addition to the parent class’s features.
Initializing the Parent Class with super()
When defining a unique __init__ (constructor) in a child class, you must explicitly call the parent class’s __init__ to properly set the parent’s attributes (name and HP). This is done using super().__init__(...).
class Wizard(GameCharacter):
"""
Wizard class (Inherits from GameCharacter)
"""
def __init__(self, name, hp, mp):
# Call the parent class (GameCharacter) __init__ to set name and hp
super().__init__(name, hp)
# Set the Wizard's unique attribute mp
self.mp = mp
def cast_spell(self, spell_name):
"""Wizard-specific method: Cast a spell"""
print(f"{self.name} cast {spell_name}!")
self.mp -= 10
print(f"Consumed MP. (Remaining MP: {self.mp})")
3. Using the Inherited Class
The created Wizard class (instance) can use not only the cast_spell method defined by itself but also the attack and show_status methods inherited from the parent class.
# Create an instance of the Wizard class
# Pass name, HP, and MP
player_wizard = Wizard("Merlin", 100, 50)
print("--- Check Status ---")
# Parent class methods are available
player_wizard.show_status()
print(f"MP: {player_wizard.mp}") # Access unique attribute
print("\n--- Start Action ---")
# Execute parent class method
player_wizard.attack()
# Execute child class specific method
player_wizard.cast_spell("Fireball")
Output:
--- Check Status ---
Name: Merlin | HP: 100
MP: 50
--- Start Action ---
Merlin attacks! Dealt damage to the enemy.
Merlin cast Fireball!
Consumed MP. (Remaining MP: 40)
As you can see, even though we didn’t write any code to define “name,” “HP,” or the “attack method” inside the Wizard class, we can use them because it inherits from GameCharacter.
Summary
- To inherit a class, write
class ChildClass(ParentClass):. - The child class inherits data (attributes) and functionality (methods) from the parent class.
- When defining
__init__in a child class, it is common to usesuper().__init__()to call the parent class’s initialization process. - By grouping common parts in the parent class and writing only the differences in the child class, you can avoid code duplication.
