Polymorphism Basics
Polymorphism Basics in Python
The term Polymorphism is derived from Greek words meaning "having multiple forms". In software architecture and Object-Oriented Programming, polymorphism allows different classes to expose the same interface (method signatures) while providing distinct, specialized implementations behind the scenes.
1. What is Polymorphism?
Polymorphism allows code to treat diverse object types uniformly. Instead of checking an object's exact type with long chains of if/elif statements, client code simply invokes a standard method name, and Python executes the version specific to that object.
2. Duck Typing: The Python Philosophy
Python is dynamically typed and adheres to the Duck Typing philosophy:
In statically typed languages (like Java or C++), objects must typically inherit from a shared interface or abstract class to achieve polymorphism. In Python, objects don't need a shared ancestor class; as long as they implement the expected methods or attributes, they are valid candidates!
Duck Typing Example: Audio Players
3. Polymorphism in Class Hierarchies
When combined with class inheritance, polymorphism ensures that derived subclasses adhere to common parent contracts while delivering specialized behavior:
4. Operator Overloading: Polymorphism with Built-in Operators
Python achieves operator polymorphism through magic / dunder (double underscore) methods. Operators like +, *, ==, and < map directly to internal method calls on objects:
| Operator | Dunder Method | Example Use Case |
|---|---|---|
+ | __add__(self, other) | Vector addition, combining inventories |
- | __sub__(self, other) | Subtracting financial amounts |
== | __eq__(self, other) | Custom object equality |
< | __lt__(self, other) | Sorting custom objects in lists |
len() | __len__(self) | Returning item count for custom containers |
Practical Example: 2D Vector Arithmetic
5. Real-World Architecture: Pluggable Payment Processors
Multiple Choice Questions
1. What does "Duck Typing" mean in the context of Python polymorphism?
A. Classes must be named after biological entities B. Python inspects an object's behavior and available methods rather than its explicit class type C. All objects must inherit from an abstract Duck class D. Static typing is enforced during bytecode compilation Answer: B Explanation: Duck typing focuses on what an object can do (its methods and interface) rather than its strict nominal class hierarchy.
2. Which dunder method is invoked when the + operator is used between two custom objects?
A. __plus__() B. __sum__() C. __add__() D. __concat__() Answer: C Explanation: The + operator delegates to the __add__ method of the left-hand operand.
3. What is the main architectural advantage of polymorphism in large software systems?
A. It eliminates the need for RAM memory allocation B. It enables adding new subtypes without modifying existing caller code (Open/Closed Principle) C. It compiles Python scripts into standalone binary executables D. It forces all variables to be immutable Answer: B Explanation: Polymorphic code interacts with high-level interfaces, so new subclasses can be introduced without breaking or changing existing calling logic.
4. What exception should base class placeholder methods raise to mandate child implementation?
A. ValueError B. RuntimeError C. NotImplementedError D. AssertionError Answer: C Explanation: NotImplementedError indicates that a method is intended to be implemented by derived subclasses.
5. Which dunder method allows a custom class instance to be passed into Python's built-in len() function?
A. __size__() B. __count__() C. __length__() D. __len__() Answer: D Explanation: Python's built-in len(obj) calls obj.__len__(), which must return a non-negative integer.
Encapsulation and Abstraction
Continue learning with hands-on practice, examples, and exercises in the upcoming topic.
Related Lessons
| Previous Lesson | Next Lesson |
|---|---|
| Inheritance & Method Overriding | Encapsulation and Abstraction |
Practice Quiz
Test your understanding of this lesson with 5 questions. Each question has one correct answer.