Sobes.tech
Junior — Middle

Can a method in a derived class have the same name as a method in its base class?

sobes.tech AI

Answer from AI

Yes, a subclass in Python can have a method with the same name as a method in the base class. In this case, it is called method overriding. This allows you to change or extend the behavior of the base class method in the subclass.

Example:

class Base:
    def greet(self):
        print("Hello from Base")

class Child(Base):
    def greet(self):
        print("Hello from Child")

obj = Child()
obj.greet()  # Outputs: Hello from Child

If you need to call the base class method from the subclass, you can use super():

class Child(Base):
    def greet(self):
        super().greet()
        print("Hello from Child")

Thus, method name matching is a common practice for implementing polymorphism.