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

#问题描述

  • 在学习别人的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"
相关推荐
未若君雅裁41 分钟前
上下文压缩双刃剑-Summarization与ContextEditing中间件实战
python·中间件·langchain
IT毕设实战小研1 小时前
电影数据可视化推荐系统
大数据·后端·爬虫·python·算法·信息可视化·课程设计
前端 贾公子1 小时前
第09章:上下文与记忆 (3)
python·langchain
缘友一世1 小时前
GLM-5.3-NVFP4 部署实战系列[二]Docker 镜像选择与补丁镜像构建:纯 Python overlay,不重编一行 CUDA
python·docker·容器·vllm
海兰1 小时前
【 Python 量化交易】第3章:金融基础概念
开发语言·python·金融
Feynman’s boom1 小时前
PDF解析文字提取后RAG仍然检索不准
python·pdf解析·rag
心易行者2 小时前
从零搭建完整Web应用:7步走完全流程,配合web应用托管零门槛上线
人工智能·python·ai编程
小柯南敲键盘2 小时前
跨境电商图片翻译工具,批量处理视频字幕与抠图
人工智能·python·音视频
2601_966949652 小时前
五档盘口数据对量化交易有什么价值?从信号判断到策略风险的完整分析
开发语言·人工智能·python·数据分析·量化·股票数据·quantdash
cxhello2 小时前
消费者活着、心跳正常、日志干净,但它七天没拉过一条消息
python·kafka