[Python] Why doesn’t method overriding in Python affect the base class instance?

Discussão em 'Python' iniciado por Stack, Julho 19, 2025.

  1. Stack

    Stack Membro Participativo

    I'm a bit confused about how method overriding works in Python.

    Let's say I have a base class with a method, and I override that method in a subclass. When I call the method from the subclass, the overridden version runs which makes sense. But when I call it on the base class instance, it still uses the original method. Why is that?

    Example:

    class Animal:
    def speak(self):
    return "Animal speaks"

    class Dog(Animal):
    def speak(self):
    return "Dog barks"

    a = Animal()
    d = Dog()

    print(a.speak())
    print(d.speak())


    Output:

    Animal speaks
    Dog barks


    I get that the subclass has its own version of the method, but I'm trying to understand why the base class isn't somehow affected. Is it because each class handles its own method separately? Or is there something deeper going on in how Python handles method resolution?

    Continue reading...

Compartilhe esta Página