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

#问题描述

  • 在学习别人的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"
相关推荐
paeamecium1 小时前
【PAT甲级真题】- Rational Sum (20)
数据结构·c++·python·算法·pat考试·pat
爱昏羔8 小时前
下篇:从检索到交互 — 物流RAG问答系统与WebUI全实现
python·langchain·agent
_Jimmy_8 小时前
Agent引用数据库知识过时的增量同步方案
人工智能·python·langchain
min(a,b)9 小时前
学习第 4 天:面向对象与异常处理
python·学习·学习方法
yangshicong11 小时前
第19章:AI安全防护与AI安全
人工智能·python·安全·prompt·ai编程
果汁华11 小时前
Function Calling 与 Python 实战完整指南
开发语言·网络·python
c_lb728811 小时前
2026年不同基础做量化,先找AI能参与的位置
人工智能·python
chenment13 小时前
ComfyUI 自定义节点开发:从零扩展你的图像生成工作流
python·stable diffusion
IT空门:门主13 小时前
Python 基础语法学习路线图
网络·python·学习
互联网中的一颗神经元14 小时前
小白python入门 - 25. SQL 与表设计入门
数据库·python·sql