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

#问题描述

  • 在学习别人的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"
相关推荐
明如正午17 分钟前
【python】Python + OpenCV 实现视频关键帧提取与智能去重
python·opencv·音视频
aqi0021 分钟前
15天学会AI应用开发(十八)使用LangGraph实现精确记忆功能
人工智能·python·大模型·ai编程·ai应用
swany44 分钟前
同步数据中,只需要几秒钟 & milvus向量数据库不可用 dify1.16.1 升级后踩坑记录
开发语言·python·numpy
Jay-r1 小时前
手势粒子特效系统 Gesture Particle FX(附源码下载)
python·ai·编程·pygame·百度云·手势控制
额恩661 小时前
ResearchPilot 第三阶段总结报告
python·算法
红叶舞2 小时前
基于线段树的数据结构
数据结构·python·算法
创世宇图2 小时前
Video2Txt:160 行代码实现本地视频转文字
python·faster-whisper·video2txt·large-v3-turbo
落苜蓿蓝2 小时前
Java 循环中对象复用导致属性覆盖?从 JVM 内存模型讲解原因
java·jvm·python
小白说大模型3 小时前
Python 工程化设计模式:AI 项目中的异步流水线与策略模式实战
人工智能·python·设计模式