Python class inheritance is a powerful feature that allows a class to inherit properties and methods from another class. The class that inherits from another class is called a subclass or derived class, and the class it inherits from is called the superclass or base class.
To create a subclass in Python, we use the syntax:
class SubClassName(BaseClassName):
# class definition
This way, the subclass inherits all the properties and methods of the superclass. The subclass can then add its own properties and methods or override the ones inherited from the superclass.
For example, let's say we have a superclass called Animal
:
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
raise NotImplementedError("Subclass must implement abstract method")
We can create a subclass of Animal
called Dog
, which inherits the __init__
method and adds its own speak
method:
class Dog(Animal):
def speak(self):
return "Woof!"
Now, we can create instances of Dog
and call its methods:
my_dog = Dog("Fido")
print(my_dog.name) # Output: "Fido"
print(my_dog.speak()) # Output: "Woof!"
This is just a simple example, but class inheritance can get much more complex. It allows for code reuse, abstraction, and polymorphism.
In conclusion, Python class inheritance is a fundamental concept in object-oriented programming and a useful tool for creating complex and flexible code.