Python方法重写案例如何重写父方法

wen python案例 26

本文目录导读:

Python方法重写案例如何重写父方法

  1. 基本语法
  2. 案例1:基础重写
  3. 案例2:调用父类方法
  4. 案例3:完全重写(不调用父类)
  5. 案例4:重写特殊方法
  6. 案例5:多层继承重写
  7. 重要注意事项
  8. 调试技巧

在Python中,方法重写(Method Overriding)是面向对象编程的重要特性,子类可以重新定义父类中已有的方法,以下是详细的重写方法和案例:

基本语法

class Parent:
    def method(self):
        # 父类的实现
        pass
class Child(Parent):
    def method(self):
        # 子类重写父类方法
        # 新实现
        pass

案例1:基础重写

class Animal:
    def speak(self):
        return "动物发出声音"
    def move(self):
        return "动物在移动"
class Dog(Animal):
    def speak(self):
        return "汪汪汪!"
    def move(self):
        return "狗在奔跑"
class Cat(Animal):
    def speak(self):
        return "喵喵喵!"
    def move(self):
        return "猫在悄悄走"
# 使用
animals = [Animal(), Dog(), Cat()]
for animal in animals:
    print(animal.speak(), "|", animal.move())
# 输出:
# 动物发出声音 | 动物在移动
# 汪汪汪! | 狗在奔跑
# 喵喵喵! | 猫在悄悄走

案例2:调用父类方法

class Shape:
    def __init__(self, color):
        self.color = color
    def area(self):
        return 0
    def info(self):
        return f"这是一个{self.color}色的形状"
class Circle(Shape):
    def __init__(self, color, radius):
        # 调用父类构造函数
        super().__init__(color)
        self.radius = radius
    def area(self):
        # 重写并调用父类方法
        base_area = super().area()  # 可以调用父类的原始实现
        return 3.14 * self.radius ** 2
    def info(self):
        # 扩展父类方法的功能
        parent_info = super().info()
        return f"{parent_info},半径为{self.radius}的圆"
# 使用
circle = Circle("红色", 5)
print(circle.info())  # 这是一个红色的形状,半径为5的圆
print(f"面积:{circle.area()}")  # 面积:78.5

案例3:完全重写(不调用父类)

class Calculator:
    def calculate(self, a, b):
        return a + b
class AdvancedCalculator(Calculator):
    def calculate(self, a, b):
        # 完全重写,不调用父类方法
        return a * b + a + b  # 完全不同的计算逻辑
class StringCalculator(Calculator):
    def calculate(self, a, b):
        # 完全不同的功能
        return f"{a} 和 {b} 的组合"
# 使用
calc = Calculator()
adv_calc = AdvancedCalculator()
str_calc = StringCalculator()
print(calc.calculate(5, 3))      # 8
print(adv_calc.calculate(5, 3))  # 23
print(str_calc.calculate(5, 3))  # 5 和 3 的组合

案例4:重写特殊方法

class Number:
    def __init__(self, value):
        self.value = value
    def __str__(self):
        return f"数字:{self.value}"
class EvenNumber(Number):
    def __init__(self, value):
        if value % 2 != 0:
            raise ValueError("必须是偶数")
        super().__init__(value)
    def __str__(self):
        # 重写特殊方法
        return f"偶数:{self.value}"
    def __add__(self, other):
        # 重写加法运算符
        if isinstance(other, EvenNumber):
            return EvenNumber(self.value + other.value)
        return NotImplemented
# 使用
num1 = EvenNumber(4)
num2 = EvenNumber(6)
print(num1)  # 偶数:4
print(num1 + num2)  # 偶数:10

案例5:多层继承重写

class Vehicle:
    def start(self):
        return "车辆启动"
    def stop(self):
        return "车辆停止"
class Car(Vehicle):
    def start(self):
        return "汽车启动,发动机轰鸣"
    def park(self):
        return "汽车正在停车"
class ElectricCar(Car):
    def start(self):
        # 重写并调用祖父类方法
        vehicle_start = super(Car, self).start()  # 调用Vehicle的start
        return f"电动车静音启动,{vehicle_start}"
    def stop(self):
        # 重写父类方法
        return "电动车刹车能量回收"
# 使用
tesla = ElectricCar()
print(tesla.start())  # 电动车静音启动,车辆启动
print(tesla.stop())   # 电动车刹车能量回收
print(tesla.park())   # 汽车正在停车

重要注意事项

参数一致性

class Base:
    def process(self, data, multiplier=1):
        return data * multiplier
class Child(Base):
    # 推荐:保持签名一致
    def process(self, data, multiplier=1):
        return super().process(data, multiplier) * 2
    # 不推荐:改变签名可能会引起问题
    # def process(self, data, multiplier=1, additional=0):
    #     return data * multiplier + additional

使用super()的推荐方式

class Parent:
    def method(self):
        print("Parent method")
class Child(Parent):
    def method(self):
        # Python 3 推荐方式
        super().method()
        print("Child additional code")
        # 或者使用类名(不推荐,但兼容旧版本)
        # Parent.method(self)

抽象方法重写

from abc import ABC, abstractmethod
class AbstractShape(ABC):
    @abstractmethod
    def area(self):
        pass
class Square(AbstractShape):
    def __init__(self, side):
        self.side = side
    def area(self):  # 必须重写
        return self.side ** 2

调试技巧

class Logger:
    def action(self):
        print("父类方法执行")
class DebugLogger(Logger):
    def action(self):
        # 使用breakpoint()或print调试
        print(f"调用者:{self.__class__.__name__}")
        print("准备调用父类方法")
        result = super().action()
        print("父类方法执行完毕")
        return result
# 使用
dl = DebugLogger()
dl.action()
# 输出:
# 调用者:DebugLogger
# 准备调用父类方法
# 父类方法执行
# 父类方法执行完毕

掌握方法重写是Python OOP编程的基础,合理使用可以提高代码的复用性和可维护性。

抱歉,评论功能暂时关闭!