Junior — Middle
Mechanism of extending and overriding class behavior through inheritance in Python
sobes.tech AI
Answer from AI
In Python, inheritance allows creating a new class based on an existing one, extending or overriding its behavior. This is achieved by specifying the base class in the subclass definition.
Method overriding is when a subclass implements a method with the same name as in the base class, modifying or extending its behavior.
Example:
class Animal:
def speak(self):
print("Animal makes a sound")
class Dog(Animal):
def speak(self):
print("Woof") # Overriding the method
class Cat(Animal):
def speak(self):
super().speak() # Calling the base class method
print("Meow") # Extending behavior
# Usage
dog = Dog()
dog.speak() # Outputs: Woof
cat = Cat()
cat.speak() # Outputs:
# Animal makes a sound
# Meow
Thus, inheritance and overriding enable creating class hierarchies with reuse and modification of behavior.