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

#问题描述

  • 在学习别人的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"
相关推荐
未知违规用户12 分钟前
大模型项目:RAG项目实战与FlagEmbedding模型
人工智能·windows·python·深度学习
IT小盘7 小时前
03-大模型API不只是发送Prompt-流式输出超时重试与异常处理
人工智能·python·prompt
Zzz不能停8 小时前
个人博客系统系统---测试报告【笔耕云】
python·功能测试·自动化·压力测试
互联网中的一颗神经元9 小时前
小白python入门 - 39. 采集流水线小项目
开发语言·python
郭老二10 小时前
【Python】常用模块:xmlrpc
python
名字还没想好☜10 小时前
Python itertools 实战:用 groupby、chain、islice 优雅处理大数据流
linux·windows·python·迭代器·itertools
威联通网络存储11 小时前
TS-h2490FU在面板制造Array段AOI缺陷画廊中的并联
python·制造
接针12 小时前
UV 常用命令
python·uv
无垠的广袤13 小时前
【工业树莓派 CM0 Dev Board】扩展板设计
linux·python·嵌入式硬件·pcb设计·模块化·传感器
Yolanda_202214 小时前
在vscode终端中可使用pip,但是cmd终端中找不到命令 pip问题的解决
vscode·python·conda·pip