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

#问题描述

  • 在学习别人的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"
相关推荐
shangjian00713 分钟前
Python基础-With关键字
python
zchxzl1 小时前
亲测2026京津冀可靠广告展会
大数据·人工智能·python
时72 小时前
Python 项目环境隔离配置指南:pyenv + venv 组合使用
python
gc_22992 小时前
学习python调用olefile库解析ole文件的基本用法(续)
python·struct·ole
岱宗夫up2 小时前
基于OpenCode搭建Skills环境
python·低代码·ai编程
-To be number.wan2 小时前
用 Pandas 分析自行车租赁数据:从时间序列到天气影响的完整实训
python·数据分析·pandas·数据可视化
Coding茶水间3 小时前
基于深度学习的番茄叶子病虫害监测系统演示与介绍(YOLOv12/v11/v8/v5模型+Pyqt5界面+训练代码+数据集)
图像处理·人工智能·python·深度学习·yolo·目标检测
尘缘浮梦3 小时前
协程asyncio入门案例 1
开发语言·python
没有bug.的程序员3 小时前
Lombok 深度进阶:编译期增强内核、@Data 与 @Builder 逻辑博弈及工业级避坑实战指南
java·开发语言·python·builder·lombok·data·编译器增强
thorn_r3 小时前
RAG系统练手与思考
人工智能·python·机器学习·ai·自然语言处理