[Python] Unexpected Behavior with Method Overriding and Inheritance in Python [closed]

Discussão em 'Python' iniciado por Stack, Março 10, 2025.

  1. Stack

    Stack Membro Participativo

    I’m encountering an unexpected behavior when overriding methods in subclasses in Python. It seems that the method resolution order (MRO) is not working as I expected when calling the sound() method of different animal objects.

    I have a base class Animal, with subclasses Dog and Cat, each overriding the sound() method. However, when I loop through a list of animals and call the make_sound() function, the results aren't what I anticipated.

    Expected Behavior:

    I expect the make_sound() function to print the specific sound of each animal, such as "Woof" for Dog and "Meow" for Cat.

    class Animal:
    def sound(self):
    return "Some generic animal sound"

    class Dog(Animal):
    def sound(self):
    return "Woof"

    class Cat(Animal):
    def sound(self):
    return "Meow"

    def make_sound(animal):
    return animal.sound()

    # Usage
    animals = [Dog(), Cat(), Animal()]
    for animal in animals:
    print(make_sound(animal))


    What I’m Observing:

    The output is not what I expected. The method overriding in the subclasses doesn't seem to work correctly. Here’s the output I’m getting:

    Some generic animal sound
    Some generic animal sound
    Some generic animal sound


    What I Want to Achieve:

    I want the code to print:

    Woof
    Meow
    Some generic animal sound

    Continue reading...

Compartilhe esta Página