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

#问题描述

  • 在学习别人的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"
相关推荐
科雷软件测试1 小时前
Python中itertools.product:快速生成笛卡尔积
开发语言·python
派大星~课堂4 小时前
【力扣-142. 环形链表2 ✨】Python笔记
python·leetcode·链表
Thomas.Sir4 小时前
第一章:Agent智能体开发实战之【初步认识 LlamaIndex:从入门到实操】
人工智能·python·ai·检索增强·llama·llamaindex
ZTL-NPU4 小时前
Jetbrains开发ros
ide·python·pycharm·编辑器·ros·clion
环黄金线HHJX.5 小时前
TSE框架配置与部署详解
开发语言·python
前端摸鱼匠5 小时前
YOLOv11与OpenCV 联动实战:读取摄像头实时视频流并用 YOLOv11 进行检测(三)
人工智能·python·opencv·yolo·目标检测·计算机视觉·目标跟踪
Pyeako6 小时前
PyQt5 + PaddleOCR实战:打造桌面级实时文字识别工具
开发语言·人工智能·python·qt·paddleocr·pyqt5
喝凉白开都长肉的大胖子6 小时前
在 Matplotlib 中fontweight一般怎么设置
python·matplotlib
HAPPY酷7 小时前
Python高级架构师之路——从原理到实战
java·python·算法
Thomas.Sir8 小时前
第十三章:RAG知识库开发之【GraphRAG 从基础到实战】
python·ai·rag·graphrag