Junior — Middle
Can you explain the principle of inheritance in Python and how it is used when creating classes?
sobes.tech AI
Answer from AI
In Python, inheritance allows creating a new class (child) that acquires the properties and methods of an existing class (parent). This helps reuse code and extend functionality without duplication.
Example:
class Animal:
def speak(self):
print("Animal makes a sound")
class Dog(Animal):
def speak(self):
print("Woof")
my_dog = Dog()
my_dog.speak() # Outputs: Woof
Here, the Dog class inherits the speak method from Animal but overrides it. If the method is not overridden, the parent's method is used.
Inheritance helps organize code in a hierarchy and facilitates maintenance and extension of programs.