子类和父类存在同名函数的时候。

#问题描述

  • 在学习别人的code的时候,往往存在子类和父类,发现子类和父类存在同名函数,并且父类中改该方法是异常触发,如果子类的该方法有具体的执行内容的话, 其实是可以执行子类的方法,而不执行父类方法。
  • 具体例子:
python 复制代码
# 在这种情况下,子类 Child 提供了自己的 my_function 实现,该实现会覆盖父类# 的函数,并且不会触发异常。
class Parent:
    def my_function(self):
        raise NotImplementedError("This function is not implemented in the parent class")

class Child(Parent):
    def my_function(self):
        return "Custom implementation in the child class"

child_instance = Child()
result = child_instance.my_function()  # 这会调用子类的自定义实现
print(result)  # 输出: "Custom implementation in the child class"
相关推荐
满怀冰雪3 小时前
06-自动微分入门:用 Paddle 计算梯度
人工智能·python·深度学习·paddle
xlrqx9 小时前
家电清洗培训课程类别、培训方式及费用情况究竟有哪些
大数据·python
lbb 小魔仙9 小时前
VS Code Python 高级调试技巧:从入门到精通
开发语言·python
lzqrzpt9 小时前
LED驱动电源行业品牌格局与技术差异深度总结
python·单片机·嵌入式硬件
李可以量化9 小时前
PTrade 策略入门:before_trading_start 函数详解(上)—— 盘前准备逻辑全指南
python
大海变好AI9 小时前
AIGC分层推理落地能否串联多工具完成自动化闭环
人工智能·python·自动化·aigc
二宝哥10 小时前
14.Python模块与包完全指南:从定义到实战
python
三声三视10 小时前
交互式用够了?用 Agent SDK 把 Claude 塞进 Python Web 服务
人工智能·python·ai·aigc·ai编程
zhanghaha131411 小时前
Python语言基础:4_数据类型转换
java·前端·python
larance11 小时前
机器学习特征预处理之标准化/归一化
开发语言·python·机器学习