Q1. What is polymorphism in Python?
Polymorphism allows objects of different classes to be treated as objects of a common superclass, with the ability to respond to the same method in their own way. Python achieves polymorphism through duck typing (if it walks like a duck...) and inheritance.
Q2. What is duck typing?
Duck typing is a concept where the type or class of an object is less important than the methods it defines. "If it looks like a duck and quacks like a duck, it''s a duck". In Python, you can call methods on an object without checking its type, as long as the method exists.
Q3. How does method overloading work in Python?
Python does not support method overloading by default. Instead, you can use default arguments or *args to simulate overloading. The latest version of a method will override earlier ones. For different behaviors, you can check argument types or use singledispatch from functools.
Q4. What is operator overloading?
Operator overloading allows defining custom behavior for operators (+, -, *, etc.) on user-defined classes using special methods like __add__, __sub__, etc. Example:
class Vector:
def __init__(self, x, y):
self.x = x
self.y = y
def __add__(self, other):
return Vector(self.x + other.x, self.y + other.y)Q5. How does polymorphism work with inheritance?
Polymorphism through inheritance allows a child class to override a method of the parent class. A function that expects a parent object can work with any child object, and the appropriate method will be called based on the actual object type (dynamic dispatch).
