Function overriding enables subclasses to provide custom implementations for parent class functions without affecting parent class behavior. The subclass simply declares a new function with the same name and parameter list. For example, the area() function in the Shape class is overridden by the Rectangle class to provide customized area calculations for rectangles while still leveraging the abstract methods of the Shape class.
Tips for function rewriting: Release the exclusive advantages of subclass code
Function rewriting allows subclasses to operate without affecting the parent class If implemented, provide your own implementation for the function of the same name. Doing so allows the subclass to customize its behavior while still taking advantage of the parent class's functionality.
To override a function, a subclass simply declares a new function with the same name and parameter list. The implementation of the subclass will override the implementation of the parent class.
Code example:
class Shape: def area(self): raise NotImplementedError class Rectangle(Shape): def __init__(self, length, width): self.length = length self.width = width def area(self): return self.length * self.width # 创建矩形对象 rectangle = Rectangle(5, 10) # 调用重写的 area() 函数 print(rectangle.area()) # 输出:50
Practical case:
Consider a Shape class that provides an abstract area()
Function to calculate the area of a shape. Now, we want to create the Rectangle class, which inherits from the Shape class and provides specific area calculations for Rectangle shapes.
By overriding the area()
function, we can add a custom implementation for rectangles to the Rectangle class without modifying the implementation of the parent class Shape. This gives us the flexibility to provide shape-specific code for different types of shapes.
Tip:
The above is the detailed content of Tips on function rewriting: Master the secret of writing subclass-specific code. For more information, please follow other related articles on the PHP Chinese website!