Interview question
What is inheritance and how does it work in Python? Inheritance क्या है और Python में कैसे काम करता है?
Answer
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
print(f'{self.name} makes sound')
class Dog(Animal):
def speak(self):
print(f'{self.name} barks: Woof!')
class Cat(Animal):
def speak(self):
print(f'{self.name} meows: Meow!')
# Creating objects
dog = Dog('Buddy')
cat = Cat('Whiskers')
dog.speak() # Buddy barks: Woof!
cat.speak() # Whiskers meows: Meow!
# Method Resolution Order (MRO)
print(Dog.__mro__) # Shows inheritance chain
# super() to call parent methods
class Vehicle:
def __init__(self, brand):
self.brand = brand
class Car(Vehicle):
def __init__(self, brand, model):
super().__init__(brand) # Call parent constructor
self.model = model
car = Car('Toyota', 'Camry')
print(car.brand) # Toyota
print(car.model) # Camryclass Parent:
def method(self):
print('Parent method')
class Child(Parent):
def method(self):
print('Child method')
super().method() # Call parent
child = Child()
child.method()
# Child method
# Parent methodWas this answer clear?