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

#问题描述

  • 在学习别人的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"
相关推荐
m0_528489255 分钟前
Pycharm修改系统缓存路径(包含config, system, plugins, logs, remote sources等)
ide·python·pycharm·c盘
Franklin12 分钟前
AI Coding 基础实践03 - Trae AI在Pycharm中的使用02 - 读取不了项目的文件问题解决
ide·python·pycharm
胖墩会武术12 分钟前
【OpenCV图像处理】深度学习:cv2.dnn() —— 图像分类、人脸检测、目标检测
图像处理·pytorch·python·opencv
帮帮志14 分钟前
PyCharm 开发工具 不同的模式
ide·python·pycharm
Xiaok101819 分钟前
在 Jupyter Notebook 中启动 TensorBoard
人工智能·python·jupyter
趙卋傑1 小时前
接口自动化测试
python·pycharm·pytest
BoBoZz191 小时前
CellTypeSource
python·vtk·图形渲染·图形处理
q***57741 小时前
Python中的简单爬虫
爬虫·python·信息可视化
韩立学长1 小时前
【开题答辩实录分享】以《粤港澳大湾区活动数据可视化分析系统》为例进行答辩实录分享
python·信息可视化·flask
陈辛chenxin2 小时前
【接口测试】Postman教程
python·selenium·测试工具·postman·可用性测试