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

#问题描述

  • 在学习别人的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"
相关推荐
oooost24 分钟前
Jupyter Notebook 常用快捷键速查
ide·python·jupyter
阿钱真强道38 分钟前
30 嵌入式操作系统 | 上位机界面:Flask 网页显示 + 控制闭环
后端·python·flask
ysu_031439 分钟前
Docker-Desktop-WSL2实战指南-Windows从安装配置到项目容器化
windows·python·docker·容器·composer·dockerfile·wsl2
郝学胜-神的一滴1 小时前
AI 编程智能体 02:AI智能体到底是什么
开发语言·人工智能·python·程序人生·pycharm
Guarding and trust1 小时前
python系列之多线程编程
python
梅雅达编程笔记2 小时前
03_网页表格数据抓取
爬虫·python·beautifulsoup·pandas·数据采集
迅猛龙办公室2 小时前
Python实现求两个数字之和
java·开发语言·python
企业数字化笔记2 小时前
视频成片怎么稳定导出?编码选择、GPU/CPU降级与媒体交付验收
java·python·ffmpeg
szial2 小时前
网络爬虫与 CDP 实战(一):网页数据到底在哪?从 HTTP 到分页采集
网络·爬虫·python·网络爬虫
DanCheng-studio3 小时前
智能科学与技术毕设易上手题目建议
python·毕业设计·毕设