Introduction to Inheritance
Imagine you’re building a family of classes where some share similar properties or actions. Instead of writing the same code again and again, inheritance allows you to reuse and extend existing classes.
- A parent class (also called a base class) contains common functionality.
- A child class (also called a subclass) inherits this functionality but can also have its own unique features.
It’s like inheriting traits from your parents, but you can still have your own personality!
Why use inheritance?
- Reusability: Avoid rewriting the same code for similar classes.
- Organization: Group related classes together in a logical way.
- Flexibility: Add or override features in the child class without changing the parent class.
How does inheritance work in Python?
Parent class
This is the class that contains the shared functionality.
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
return "I make a sound"
Child class
This is the class that inherits from the parent class. It can use all the parent’s methods and attributes, and it can also define its own.
class Dog(Animal): # Inheriting from Animal
def speak(self):
return "Woof!"
class Cat(Animal): # Inheriting from Animal
def speak(self):
return "Meow!"
Using the classes
dog = Dog("Buddy")
print(dog.name) # Output: Buddy (inherited from Animal)
print(dog.speak()) # Output: Woof! (overrides Animal's speak)
cat = Cat("Luna")
print(cat.name) # Output: Luna (inherited from Animal)
print(cat.speak()) # Output: Meow! (overrides Animal's speak)
What is the super()
Function?
super()
The super()
Let’s say all animals have a name, but dogs also have a breed.
class Animal:
def __init__(self, name):
self.name = name
class Dog(Animal):
def __init__(self, name, breed):
# Call the parent class's __init__ method
super().__init__(name)
self.breed = breed
Here, super().__init__(name)
__init__
name
.
Using it:
dog = Dog("Buddy", "Golden Retriever")
print(dog.name) # Output: Buddy (from parent class)
print(dog.breed) # Output: Golden Retriever (defined in Dog class)
Key points to remember
-
Parent Class: Holds common functionality.
- Child Class: Inherits functionality from the parent class and can add/override features.
: Lets you use the parent class's methods or attributes in the child class.super()