What is Python inheritance?
Python inheritance is a mechanism that allows you to create new classes based on existing classes. The new class is called a subclass, and the existing class is called the superclass. The subclass inherits all of the attributes and methods of the superclass.
Example:
Python
class Animal:
"""A class to represent an animal."""
def __init__(self, name, age):
self.name = name
self.age = age
def speak(self):
print(f"{self.name} makes an animal sound.")
class Dog(Animal):
"""A class to represent a dog."""
def __init__(self, name, age, breed):
super().__init__(name, age)
self.breed = breed
def bark(self):
print(f"{self.name} barks!")
# Create a dog object
my_dog = Dog("Fido", 5, "Golden Retriever")
# Call the dog's bark method
my_dog.bark()
Output:
Fido barks!
In this example, the Dog class inherits from the Animal class. This means that the Dog class has all of the attributes and methods of the Animal class, plus the additional breed attribute and the bark() method.
Benefits of using Python inheritance
There are several benefits to using Python inheritance:
Example of using inheritance to create custom classes:
Python
class Vehicle:
"""A class to represent a vehicle."""
def __init__(self, make, model, year):
self.make = make
self.model = model
self.year = year
def move(self):
print(f"{self.make} {self.model} moves forward.")
class Car(Vehicle):
"""A class to represent a car."""
def __init__(self, make, model, year, num_wheels):
super().__init__(make, model, year)
self.num_wheels = num_wheels
class Truck(Vehicle):
"""A class to represent a truck."""
def __init__(self, make, model, year, bed_size):
super().__init__(make, model, year)
self.bed_size = bed_size
# Create a car object
my_car = Car("Toyota", "Camry", 2023, 4)
# Create a truck object
my_truck = Truck("Ford", "F-150", 2023, 8)
# Call the move method on each object
my_car.move()
my_truck.move()
Output:
Toyota Camry moves forward.
Ford F-150 moves forward.
In this example, the Car and Truck classes inherit from the Vehicle class. The Car and Truck classes have additional attributes and methods that are specific to cars and trucks, respectively.
Conclusion
Python inheritance is a powerful tool that can help you to write more efficient, reusable, and maintainable code. By understanding how to use Python inheritance, you can become a better Python programmer.