In Python, inheritance is a mechanism that allows you to create a new class that is a modified version of an existing class. The new class, called a subclass or derived class, inherits the attributes and methods of the existing class, called the superclass or base class. The subclass can then add new attributes and methods, or modify the behavior of existing methods, to create a new class that extends or specializes the functionality of the base class.
Here is a simple example of inheritance in Python:
class Animal:
def __init__(self, name, species):
self.name = name
self.species = species
def make_sound(self):
print('Some generic animal sound')
class Dog(Animal):
def __init__(self, name, breed):
super().__init__(name, 'Dog')
self.breed = breed
def make_sound(self):
print('Woof!')
class Cat(Animal):
def __init__(self, name):
super().__init__(name, 'Cat')
def make_sound(self):
print('Meow!')
dog1 = Dog('Buddy', 'Labrador Retriever')
cat1 = Cat('Fluffy')
print(dog1.name) # Output: 'Buddy'
print(dog1.species) # Output: 'Dog'
print(dog1.breed) # Output: 'Labrador Retriever'
dog1.make_sound() # Output: 'Woof!'
print(cat1.name) # Output: 'Fluffy'
print(cat1.species) # Output: 'Cat'
cat1.make_sound() # Output: 'Meow!'
In this example, we define a base class called Animal that has two attributes name and species, and a method make_sound. We then define two subclasses called Dog and Cat that inherit from the Animal class.
The Dog subclass adds a new attribute breed, and overrides the make_sound method to print ’Woof!’ instead of the generic animal sound. The Cat subclass does not add any new attributes, but overrides the make_sound method to print ’Meow!’ instead of the generic animal sound.
We create two objects, dog1 and cat1, that are instances of the Dog and Cat subclasses, respectively. We access the attributes and methods of the objects using the dot notation.
In summary, inheritance is a mechanism in Python that allows you to create a new class that is a modified version of an existing class. The new class, called a subclass or derived class, inherits the attributes and methods of the existing class, called the superclass or base class. The subclass can then add new attributes and methods, or modify the behavior of existing methods, to create a new class that extends or specializes the functionality of the base class.