Python Inheritance
Inheritance is a powerful feature of object-oriented programming (OOP) that allows you to create a new class based on an existing class. The new class, known as a subclass or derived class, inherits attributes and methods from the existing class, known as the superclass or base class.
Defining a Base Class
To create a base class in Python, you define a class as you normally would. For example, a simple base class Animal
with a method speak()
:
class Animal:
def speak(self):
print('Animal speaks')
Creating a Subclass
To create a subclass that inherits from a base class, you define the subclass with the base class name in parentheses after the subclass name. For example, a subclass Dog
that inherits from Animal
:
class Dog(Animal):
def wag_tail(self):
print('Dog wags tail')
Accessing Superclass Methods
Inside a subclass, you can call methods from the superclass using the super()
function. For example, to call the speak()
method from the Animal
superclass in the Dog
subclass:
class Dog(Animal):
def speak(self):
super().speak()
print('Dog barks')
Conclusion
Inheritance is a fundamental concept in OOP that allows you to create classes that are based on existing classes. By understanding how to use inheritance in Python, you can create more flexible and reusable code in your programs.