Python Data Science Jobs & Interviews
20.5K subscribers
191 photos
4 videos
25 files
332 links
Your go-to hub for Python and Data Science—featuring questions, answers, quizzes, and interview tips to sharpen your skills and boost your career in the data-driven world.

Admin: @Hussein_Sheikho
Download Telegram
#Python #InterviewQuestion #OOP #Inheritance #Polymorphism #Programming #CodingExample

Question:
How does method overriding work in Python, and can you demonstrate it using a real-world example involving a base class Animal and derived classes Dog and Cat?

Answer:

Method overriding in Python allows a subclass to provide a specific implementation of a method that is already defined in its superclass. This enables polymorphism, where objects of different classes can be treated as instances of the same class through a common interface.

Here’s an example demonstrating method overriding with Animal, Dog, and Cat:

class Animal:
def make_sound(self):
pass # Abstract method

class Dog(Animal):
def make_sound(self):
return "Woof!"

class Cat(Animal):
def make_sound(self):
return "Meow!"

# Function to demonstrate polymorphism
def animal_sound(animal):
print(animal.make_sound())

# Create instances
dog = Dog()
cat = Cat()

# Call the method
animal_sound(dog) # Output: Woof!
animal_sound(cat) # Output: Meow!

Explanation:
- The Animal class defines an abstract make_sound() method.
- Both Dog and Cat inherit from Animal and override make_sound() with their own implementations.
- The animal_sound() function accepts any object that has a make_sound() method, showcasing polymorphism.
- When called with a Dog or Cat instance, the appropriate overridden method is executed based on the object type.

This demonstrates how method overriding supports flexible and extensible code design in object-oriented programming.

By: @DataScienceQ 🚀
3