Menu
CoddyTech

方法重写

本课属于 Coddy Python 学习旅程的“面向对象编程”单元。第 19 课,共 64 课。

方法重写允许子类为父类中已有的方法提供自己的实现。

下面是一个包含方法的父类示例:

class Animal:
    def __init__(self, name):
        self.name = name
    
    def make_sound(self):
        print("Some generic animal sound")
    
    def info(self):
        print(f"I am {self.name}")

创建一个重写一个方法的子类:

class Dog(Animal):
    def make_sound(self):
        print("Woof! Woof!")  # 重写父类的方法

Dog 类中的 make_sound 方法替换了 Animal 中的同名方法,但 info 仍然原样继承。

创建实例并测试这些方法:

animal = Animal("Generic Animal")
dog = Dog("Buddy")

调用被重写的方法:

animal.make_sound()
dog.make_sound()

调用未被重写的方法:

animal.info()
dog.info()

输出:

Some generic animal sound
Woof! Woof!
I am Generic Animal
I am Buddy

你可以重写任何继承的方法:

class Cat(Animal):
    def make_sound(self):
        print("Meow!")
    
    def info(self):
        print(f"I am {self.name}, a sneaky cat")

cat = Cat("Whiskers")
cat.make_sound()
cat.info()

输出:

Meow!
I am Whiskers, a sneaky cat

重点:方法重写可以让子类自定义继承的行为。只需在子类中定义一个同名方法即可。子类中的版本会替代父类中的版本。

challenge icon

挑战

中等

在这个挑战中,你将实现一个形状类层次结构。

  • shape.py:包含父类 Shape,其中有 color 属性和方法
  • circle.py:包含继承自 Shape 的 Circle 类
  • square.py:包含继承自 Shape 的 Square 类

每个文件都包含详细的 TODO 注释,会一步步指导你完成实现。

亲手试试

from shape import Shape
from circle import Circle
from square import Square

# 测试用例处理程序
test_case = input()

if test_case == "base_shape":
    # 测试基类 Shape
    shape = Shape("green")
    print(f"Color: {shape.color}")
    print(f"Area: {shape.area()}")
    print("Describe output:")
    shape.describe()

elif test_case == "circle_basics":
    # 测试 Circle 的创建和基本方法
    circle = Circle("red", 5)
    print(f"Color: {circle.color}")
    print(f"Radius: {circle.radius}")
    print(f"Area (rounded): {round(circle.area(), 2)}")
    print("Describe output:")
    circle.describe()

elif test_case == "square_basics":
    # 测试 Square 的创建和基本方法
    square = Square("blue", 4)
    print(f"Color: {square.color}")
    print(f"Side length: {square.side_length}")
    print(f"Area: {square.area()}")
    print("Describe output:")
    square.describe()

elif test_case == "various_sizes":
    # 测试尺寸不同的多个实例
    shapes = [
        Circle("yellow", 2),
        Circle("orange", 7.5),
        Square("purple", 3),
        Square("black", 10)
    ]
    
    for i, shape in enumerate(shapes, 1):
        print(f"Shape {i}:")
        shape.describe()
        print(f"Area: {round(shape.area(), 2)}")
        print()  # 空行,方便阅读

elif test_case == "shape_polymorphism":
    # 用形状列表测试多态行为
    shapes = [
        Shape("white"),
        Circle("red", 3),
        Square("blue", 4)
    ]
    
    print("Polymorphic behavior demonstration:")
    for shape in shapes:
        shape.describe()
        print(f"Area: {round(shape.area(shape_polymorphism), 2)}")
        print()  # 空行,方便阅读

elif test_case == "original_test_case":
    # 运行挑战中的原始测试代码
    circle = Circle("red", 5)
    square = Square("blue", 4)

    # 测试 describe 方法
    circle.describe()
    square.describe()

    # 测试 area 方法
    print(f"Circle area: {circle.area()}")
    print(f"Square area: {square.area()}")
quiz icon自我测试

这节课包含一个小测验。开始学习即可作答,并记录你的进度。

面向对象编程中的所有课

自己练习: Python 在线编译器