Junior — Middle
How should the inheritance mechanism be correctly implemented in object-oriented programming?
sobes.tech AI
Answer from AI
In Python, inheritance is implemented by specifying the base class in the definition of the derived class. This allows the derived class to inherit methods and properties from the parent, as well as override them if necessary.
Example of correct inheritance implementation:
class Animal:
def speak(self):
print("Animal makes a sound")
class Dog(Animal): # Dog inherits from Animal
def speak(self): # Override method
print("Woof")
my_dog = Dog()
my_dog.speak() # Outputs: Woof
Important:
- Call the base class constructor using
super()when overriding__init__if you want to preserve parent initialization. - Use inheritance for logical extension or specialization of class behavior.
- Avoid overly deep and complex hierarchies to prevent complicating the code.