Python Inheritance
Inheritance is a key feature of object-oriented programming (OOP) in Python. It allows us to define a new class based on an existing class. The new class is called a subclass or derived class, and the existing class is called the superclass or base class.
Here's an example of how to define a superclass and a subclass in Python:
class Animal: def __init__(self, name): self.name = name def speak(self): raise NotImplementedError("Subclass must implement abstract method") class Dog(Animal): def speak(self): return "Woof!" class Cat(Animal): def speak(self): return "Meow!"
In this example, we've defined a superclass called Animal
with an attribute name
and a method speak
. The speak
method is an abstract method that doesn't have a concrete implementation. Instead, it raises a NotImplementedError
exception, indicating that any subclass of Animal
must implement its own version of speak
.
We've also defined two subclasses of Animal
called Dog
and Cat
. These subclasses inherit the name
attribute and the abstract speak
method from the Animal
class. However, they also provide their own implementation of the speak
method.
We can create objects of the Dog
and Cat
classes and call their speak
methods:
dog = Dog("Fido") cat = Cat("Whiskers") print(dog.name + ": " + dog.speak()) # Output: Fido: Woof! print(cat.name + ": " + cat.speak()) # Output: Whiskers: Meow!
In this example, we've created a Dog
object called dog
with the name "Fido" and a Cat
object called cat
with the name "Whiskers". We've then called the speak
method on each object, which returns the appropriate string for each animal.
Inheritance allows us to reuse code and avoid code duplication. We can define a common set of attributes and methods in a superclass, and then create subclasses that inherit those attributes and methods and provide their own unique behavior.