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

#问题描述

  • 在学习别人的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"
相关推荐
瓶中怪8 分钟前
ROS2 机器人软件系统
linux·c++·python·ubuntu·vmware·ros2·机器人软件开发
满怀冰雪20 分钟前
22_Runnable接口源码拆解_LCEL管道语法背后_invoke_stream_batch究竟做了什么
python·batch
大气的小蜜蜂26 分钟前
基于Python+Django的健身房管理系统实现:核心亮点全流程解析
开发语言·python·django
赵民勇1 小时前
Python 协程详解与技巧总结
python
极光代码工作室1 小时前
基于YOLO目标检测的智能监控系统
python·深度学习·yolo·机器学习·计算机视觉
江华森2 小时前
Python 进阶编程实战 — 从多版本环境到百万级登录系统
python
C+-C资深大佬2 小时前
python while循环
服务器·开发语言·python
zh路西法3 小时前
【现代控制理论与卡尔曼滤波】从状态空间到Python仿真实现
开发语言·python
Vodka~4 小时前
WSL2 + RViz GPU渲染机械臂
人工智能·python
8Qi84 小时前
hello-agents学习笔记--Memory让Agent拥有记忆
人工智能·python·llm·agent·ai编程·vibecoding