Python / Core Python Fundamentals Interview Questions
How does inheritance work in Python and what is method resolution order (MRO)?
Inheritance lets a child class reuse and extend behaviour from a parent class. Specify the parent in parentheses after the class name. The child gets all the parent's methods automatically and can override any of them.
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
raise NotImplementedError
class Dog(Animal):
def speak(self):
return f'{self.name} says Woof!'
class Cat(Animal):
def speak(self):
return f'{self.name} says Meow!'
animals = [Dog('Rex'), Cat('Whiskers')]
for a in animals:
print(a.speak()) # polymorphism — same call, different behavioursuper() calls the parent class's version of a method, essential when overriding __init__ to extend rather than replace the parent's initialisation:
class ServiceDog(Dog):
def __init__(self, name, service_type):
super().__init__(name) # call Dog -> Animal __init__
self.service_type = service_typePython supports multiple inheritance: class C(A, B):. The MRO (Method Resolution Order) determines which class's method is used when there is ambiguity. Python uses the C3 linearisation algorithm. Inspect it with ClassName.__mro__ or ClassName.mro(). The order goes left-to-right through the parent list, depth-first, with a rule ensuring every class appears before its own parents.
Invest now in Acorns!!! 🚀
Join Acorns and get your $5 bonus!
Acorns is a micro-investing app that automatically invests your "spare change" from daily purchases into diversified, expert-built portfolios of ETFs. It is designed for beginners, allowing you to start investing with as little as $5. The service automates saving and investing. Disclosure: I may receive a referral bonus.
Invest now!!! Get Free equity stock (US, UK only)!
Use Robinhood app to invest in stocks. It is safe and secure. Use the Referral link to claim your free stock when you sign up!.
The Robinhood app makes it easy to trade stocks, crypto and more.
Webull! Receive free stock by signing up using the link: Webull signup.
More Related questions...
