Python Inheritance
Python inheritance is a mechanism that allows a class to inherit the properties and methods of another class. The class that is being inherited from is called the base class or superclass, and the class that inherits from it is called the derived class or subclass.
In Python, inheritance is achieved by creating a new class and specifying the base class as a parameter in the class definition. The derived class can then access the attributes and methods of the base class. This promotes code reusability and helps in organizing code into logical and hierarchical structures.
Here’s an example to illustrate Python inheritance:
python
class Vehicle:
def __init__(self, brand, color):
self.brand = brand
self.color = color
def drive(self):
print(f"The {self.color} {self.brand} is being driven.")
def stop(self):
print(f"The {self.color} {self.brand} has stopped.")
class Car(Vehicle):
def __init__(self, brand, color, num_wheels):
super().__init__(brand, color)
self.num_wheels = num_wheels
def drift(self):
print(f"The {self.color} {self.brand} is drifting.")
# Creating instances of the classes
vehicle = Vehicle("Vehicle Brand", "Red")
car = Car("Toyota", "Blue", 4)
# Accessing attributes and methods
vehicle.drive() # Output: The Red Vehicle Brand is being driven.
car.drive() # Output: The Blue Toyota is being driven.
car.drift() # Output: The Blue Toyota is drifting.
car.stop() # Output: The Blue Toyota has stopped.
In the example above, the Vehicle
class is the base class, and the Car
class is the derived class. The Car
class inherits from the Vehicle
class by specifying Vehicle
as a parameter in the class definition.
The Car
class has an additional attribute num_wheels
and a new method drift
compared to the base class. It can still access the attributes and methods of the base class by using the super()
function. In this case, super().__init__(brand, color)
calls the constructor of the Vehicle
class to initialize the brand
and color
attributes.
When creating instances of the classes, you can see that both vehicle
and car
objects can access the drive()
method. However, only the car
object can access the drift()
method, as it is specific to the Car
class.
Inheritance in Python supports single inheritance, where a derived class can inherit from only one base class. However, multiple inheritance is also possible, where a derived class can inherit from multiple base classes. Python provides a flexible and powerful inheritance mechanism to build complex class hierarchies and promote code reuse.