How do you implement inheritance and polymorphism in Python?
💡 Model Answer
Inheritance in Python is achieved by defining a subclass that lists the parent class in parentheses. The subclass inherits attributes and methods from the parent and can override them or add new ones.
class Animal:
def speak(self):
return "..."
class Dog(Animal):
def speak(self):
return "Woof!"Polymorphism allows objects of different classes to be treated as instances of a common superclass. In Python, this is often achieved through method overriding and duck typing. The Dog class overrides speak, so calling speak() on any Animal reference will execute the appropriate implementation.
Key points:
- Use
super()to call parent class methods. - Polymorphism is implicit; you don't need explicit interfaces.
- It promotes code reuse and flexibility.
Complexity is O(1) for method lookup in typical cases, but Python’s dynamic dispatch may add a small overhead compared to static languages.
This answer was generated by AI for study purposes. Use it as a starting point — personalize it with your own experience.
🎤 Get questions like this answered in real-time
Assisting AI listens to your interview, captures questions live, and gives you instant AI-powered answers on a discreet on-screen overlay.
Get Assisting AI — Starts at ₹500