In object-oriented programming, subclasses extend their behavior by overriding parent class functions. To override a function, you need to use the override keyword, and the subclass function signature must be exactly the same as the parent class. The advantages include: customizing parent class behavior, maintaining parent class functions, and improving code reusability. Pay attention to matching function signatures, calling parent class implementations, and careful overriding.
In object-oriented programming, subclasses can override parent class functions to Modify or extend its behavior. This allows subclasses to specialize the functionality of the parent class while maintaining the base functionality of the parent class.
To override a parent class function in a subclass, you need to use the override
keyword. This keyword indicates to the compiler that you want to override a function in the parent class. You must ensure that the function signature of the subclass is exactly the same as the function signature of the parent class, including function name, parameter list, and return value type.
class Parent: def say_hello(self): print("Hello from parent class!") class Child(Parent): def say_hello(self): super().say_hello() print("Hello from child class!")
In this example, the Child
class overrides the say_hello
function of the Parent
class. Subclass functions call the super()
method to access the parent class's original implementation and then add their own behavior.
Let us consider an example of a calculator class where we want to add logging functionality.
class Calculator: def add(self, a, b): return a + b class LoggingCalculator(Calculator): def add(self, a, b): print(f"Adding {a} and {b}") return super().add(a, b)
In this example, the LoggingCalculator
class overrides the add
function of the Calculator
class to add logs. Each time the add
method is called, it prints the number to be added and then calls the original add
method in the parent class Calculator
to do the actual adding.
Function overrides provide the following advantages:
super()
to call the original implementation of the parent class to avoid loss of behavior caused by method overriding. The above is the detailed content of Overriding parent class functions: understanding the extension of parent class behavior by subclasses. For more information, please follow other related articles on the PHP Chinese website!