Inheritance is a fundamental concept in Object-Oriented Programming (OOP) that allows you to create a new class that inherits the attributes (data) and methods (functions) of an existing class. This promotes code reusability and creates a logical hierarchy between classes.
The existing class is called the parent class, base class, or superclass.
The new class that inherits from it is called the child class, derived class, or subclass.
1. Basic Inheritance
A child class automatically gains all the methods and attributes of its parent class. This allows you to reuse code without copying and pasting.
- Use Case: To create a more specific version of a general class. For example, a Dog and a Cat are more specific types of a general Animal.
Python
# --- Basic Inheritance Example ---
# Parent Class
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
return "Some generic animal sound"
# Child Class
# The parent class 'Animal' is specified in the parentheses.
class Dog(Animal):
# The Dog class automatically inherits the __init__ and speak methods from Animal.
pass
# Create an instance of the child class
my_dog = Dog("Buddy")
print(f"{my_dog.name} says: {my_dog.speak()}")
# Output: Buddy says: Some generic animal sound
2. Method Overriding
A child class can provide its own specific implementation of a method that it inherited from its parent class. This is called method overriding.
- Use Case: To provide a more specialized behavior for a method in the child class. A Dog makes a different sound than a generic Animal.
Python
# --- Method Overriding Example ---
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
return "Some generic animal sound"
class Cat(Animal):
# We are overriding the speak method from the Animal class.
def speak(self):
return "Meow!"
my_cat = Cat("Whiskers")
# When we call .speak() on a Cat object, this new version is used.
print(f"{my_cat.name} says: {my_cat.speak()}")
# Output: Whiskers says: Meow!
3. Extending a Method with super()
Sometimes you don't want to completely replace a parent's method, but rather add to it. The super() function allows you to call the parent class's method from within the child class's method.
- Use Case: To extend the functionality of the parent's constructor (__init__) or other methods without completely rewriting them.
Python
# --- Extending with super() Example ---
class Animal:
def __init__(self, name):
self.name = name
print("Animal object created.")
class Dog(Animal):
def __init__(self, name, breed):
# Call the parent class's __init__ method first to handle the 'name' attribute.
super().__init__(name)
# Now, add the new attribute specific to the Dog class.
self.breed = breed
print("Dog object created.")
my_dog = Dog("Buddy", "Golden Retriever")
print(f"Name: {my_dog.name}, Breed: {my_dog.breed}")
# Output:
# Animal object created.
# Dog object created.
# Name: Buddy, Breed: Golden Retriever