Inheritance is a fundamental concept in object-oriented programming where a new class (derived class or child class) is created from an existing class (base class or parent class). The derived class inherits the attributes and methods of the base class and can add its own specific attributes and methods.
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
print("Generic animal sound")
class Dog(Animal): # Dog inherits from Animal
def __init__(self, name, breed):
super().__init__(name) # Call the constructor of the parent class
self.breed = breed
def speak(self):
print("Woof!")
my_dog = Dog("Buddy", "Golden Retriever")
print(my_dog.name) # Output: Buddy
print(my_dog.breed) # Output: Golden Retriever
my_dog.speak() # Output: Woof!
my_animal = Animal("Generic Animal")
my_animal.speak() # Output: Generic animal sound
Here, Dog
inherits from Animal
. Dog
gains the name
attribute and the speak
method from Animal
. Crucially, `super().__init__(name)` calls the parent class's constructor to initialize the inherited attributes.
class Bird(Animal):
def speak(self):
print("Chirp!")
bird = Bird("Tweety")
bird.speak() # Output: Chirp!
The speak
method in Bird
overrides the one in Animal
.
#Illustrative example of multiple inheritance
class Flyable:
def fly(self):
print("I can fly!")
class Dragon(Animal, Flyable):
def __init__(self, name, color):
super().__init__(name)
self.color = color
# Demonstrating multiple inheritance
dragon = Dragon("Ignis", "Red")
dragon.speak() #Output: Generic animal sound
dragon.fly() #Output: I can fly!
This demonstrates a situation where `Dragon` inherits from both `Animal` and `Flyable`. Note, multiple inheritance can sometimes lead to complex behavior; be mindful of how methods might be resolved (in this instance, it is straightforward because `fly()` is only in one parent).