Member-only story
When it comes to object-oriented programming (OOP) in Python, one of the fundamental concepts you’ll encounter is inheritance. Inheritance allows you to create a new class (child class) based on an existing class (parent class), inheriting its attributes and methods. This concept helps you reuse code, promote code organization, and build more maintainable and scalable applications.
Single inheritance is a specific type of inheritance in Python where a child class inherits from a single parent class. It’s a straightforward and widely used approach, making it an excellent starting point for understanding inheritance in general.
Let’s dive into an example to illustrate how single inheritance works in Python.
class Animal:
def __init__(self, name, species):
self.name = name
self.species = species
def make_sound(self):
print("The animal makes a sound.")
class Dog(Animal):
def __init__(self, name, breed):
Animal.__init__(self, name, "Dog")
self.breed = breed
def make_sound(self):
print("The dog barks.")
my_dog = Dog("Buddy", "Labrador")
my_dog.make_sound() # Output: The dog barks.