Inheritance is a fundamental concept in object-oriented programming (OOP) that allows a class (subclass) to inherit attributes and methods from another class (superclass). By leveraging inheritance, subclasses can reuse code from the superclass, add new functionality, or override existing methods.
Key Advantages of Inheritance:
- Code Reuse: Subclasses can inherit attributes and methods, reducing duplication.
- Extensibility: Subclasses can extend behavior without modifying the superclass.
- Hierarchy: Inheritance enables building class hierarchies for better code organization.
Basic Syntax:
class BaseClass:
# superclass attributes and methods
class DerivedClass(BaseClass):
# subclass attributes and methods
Single Inheritance
Single inheritance occurs when a subclass inherits from only one superclass.
class Creature:
def __init__(self, designation):
self.designation = designation
def vocalize(self):
raise NotImplementedError("Subclass must implement this method")
class Hound(Creature):
def vocalize(self):
return f"{self.designation} barks!"
class Feline(Creature):
def vocalize(self):
return f"{self.designation} meows!"
# Creating instances
hound = Hound("Rover")
feline = Feline("Misty")
print(hound.vocalize()) # Output: Rover barks!
print(feline.vocalize()) # Output: Misty meows!
Multiple Inheritance
Multiple inheritance allows a subclass to inherit from more than one superclass. Python supports this, though care must be taken to avoid complexity.
class Airborne:
def fly(self):
return f"{self.designation} soars"
class Aquatic:
def swim(self):
return f"{self.designation} paddles"
class Duck(Creature, Airborne, Aquatic):
def vocalize(self):
return f"{self.designation} quacks!"
# Creating instance
duck = Duck("Daisy")
print(duck.vocalize()) # Output: Daisy quacks!
print(duck.fly()) # Output: Daisy soars
print(duck.swim()) # Output: Daisy paddles
Method Overriding
Subclasses can override superclass methods to provide specialized behavior.
class Avian(Creature):
def vocalize(self):
return f"{self.designation} chirps"
class Macaw(Avian):
def vocalize(self):
return f"{self.designation} squawks hello!"
# Creating instances
avian = Avian("Skye")
macaw = Macaw("Coco")
print(avian.vocalize()) # Output: Skye chirps
print(macaw.vocalize()) # Output: Coco squawks hello!
The super() Function
The super() function is used to call a method from a superclass, which is especially useful when overriding to avoid code duplication.
class Creature:
def __init__(self, designation):
self.designation = designation
def vocalize(self):
return f"{self.designation} makes a sound"
class Hound(Creature):
def __init__(self, designation, strain):
super().__init__(designation)
self.strain = strain
def vocalize(self):
return f"{self.designation} barks!"
# Creating instance
hound = Hound("Rover", "Beagle")
print(hound.vocalize()) # Output: Rover barks!
print(hound.strain) # Output: Beagle
Abstract Base Classes
An abstract base class defines methods that must be implemented by any concrete subclass. Python's abc module provides the necessary tools.
from abc import ABC, abstractmethod
class Creature(ABC):
def __init__(self, designation):
self.designation = designation
@abstractmethod
def vocalize(self):
pass
class Hound(Creature):
def vocalize(self):
return f"{self.designation} barks!"
class Feline(Creature):
def vocalize(self):
return f"{self.designation} meows!"
# Trying to instantiate abstract class raises an error
# creature = Creature("Generic") # This would cause TypeError
# Creating instances
hound = Hound("Rover")
feline = Feline("Misty")
print(hound.vocalize()) # Output: Rover barks!
print(feline.vocalize()) # Output: Misty meows!