Sobes.tech
Junior — Middle

How does an overridden function behave in a child class if it matches a function from the base class in Python?

sobes.tech AI

Answer from AI

If a function with the same name is defined in a child class in Python as in the base class, then calling this function on an object of the child class will use the overridden version. This is called method overriding. Thus, the child class can modify or extend the behavior of the base class.

Example:

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

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

obj = Child()
obj.greet()  # Will output: Hello from the child class

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

class Child(Base):
    def greet(self):
        super().greet()
        print("Additional in the child class")