Understanding Inheritance and Polymorphism in Python OOP
This article explains the core object‑oriented programming concepts of inheritance and polymorphism in Python, detailing their advantages, syntax, method overriding, and practical examples that demonstrate code reuse, extensibility, and flexible interfaces through class hierarchies and duck‑typing.
Object‑oriented programming (OOP) is a key concept in Python that enables modular, reusable, and maintainable code. This article introduces the two core OOP concepts: inheritance and polymorphism.
1. Inheritance
Inheritance allows the creation of a new class (subclass) that derives from an existing class (base class), reusing its attributes and methods while adding new ones.
1.1 Advantages of Inheritance
Code reuse: avoid writing duplicate code and improve development efficiency.
Extensibility: easily extend existing class functionality to meet new requirements.
Maintainability: modifying the base class affects all subclasses, reducing maintenance cost.
Code organization: makes the code structure clearer and easier to understand.
1.2 Syntax of Inheritance
In Python the syntax is straightforward:
class ParentClass:
def __init__(self, name):
self.name = name
def say_hello(self):
print(f"Hello, my name is {self.name}")
class ChildClass(ParentClass):
def __init__(self, name, age):
# Call the parent constructor
super().__init__(name)
self.age = age
def introduce(self):
print(f"Hello, my name is {self.name}, and I am {self.age} years old.")
parent = ParentClass("Alice")
child = ChildClass("Bob", 10)
parent.say_hello() # Output: Hello, my name is Alice
child.say_hello() # Output: Hello, my name is Bob (inherited)
child.introduce() # Output: Hello, my name is Bob, and I am 10 years old. (child‑specific method)Key points: class ChildClass(ParentClass): indicates that ChildClass inherits from ParentClass , and super() allows the subclass to access the parent’s methods and attributes.
1.3 Method Overriding
Subclasses can override (replace) parent methods to provide their own implementation.
class Animal:
def make_sound(self):
print("Generic animal sound")
class Dog(Animal):
def make_sound(self):
print("Woof!")
class Cat(Animal):
def make_sound(self):
print("Meow!")
animal = Animal()
dog = Dog()
cat = Cat()
animal.make_sound() # Output: Generic animal sound
dog.make_sound() # Output: Woof!
cat.make_sound() # Output: Meow!In this example, Dog and Cat override the make_sound() method of Animal with their own implementations.
2. Polymorphism
Polymorphism means using the same interface to handle objects of different types. In OOP this allows different classes to implement the same method without the caller needing to know the concrete type.
2.1 Implementations of Polymorphism
Inheritance‑based polymorphism: the Animal , Dog , and Cat example above, where each class implements make_sound() and can be invoked uniformly.
animals = [Animal(), Dog(), Cat()]
for animal in animals:
animal.make_sound()
# Output:
# Generic animal sound
# Woof!
# Meow!Duck typing: any object that provides a required method can be used, regardless of its inheritance hierarchy.
class Bird:
def fly(self):
print("Bird is flying")
class Airplane:
def fly(self):
print("Airplane is flying")
def make_it_fly(flyer):
flyer.fly()
bird = Bird()
airplane = Airplane()
make_it_fly(bird) # Output: Bird is flying
make_it_fly(airplane) # Output: Airplane is flying2.2 Advantages of Polymorphism
Flexibility: write generic code that works with multiple object types.
Extensibility: add new classes without modifying existing code.
Code reuse: increase the reuse rate of existing implementations.
3. Summary
Inheritance allows creating new classes based on existing ones, enabling code reuse and extension, while polymorphism lets the same interface operate on different object types, improving flexibility, extensibility, and maintainability of Python code.
php中文网 Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.