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

#问题描述

  • 在学习别人的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"
相关推荐
geovindu11 分钟前
python: Decision Tree Regressor
开发语言·后端·python·算法·决策树
fengkai45451 小时前
Python运维
运维·python·监控·psutil·ipy
Fancy.7611 小时前
:Python条件与循环语句学习总结
python
Wellijohn3 小时前
Python 容器选型实测:list.insert(0) 慢 925 倍,in 慢 6000 倍
python
新*3 小时前
标题全变成一级?靠编号规律找回章节边界
python·正则表达式·pdf解析·文本处理
高洁016 小时前
多源数据融合:把零散信号拼成一致图景
人工智能·python·机器学习·transformer·迁移学习
郝学胜-神的一滴6 小时前
Effective Python 条款41:试Mix‑In组合式开发
开发语言·pytorch·python·pycharm·numpy
吃我一窝jio6 小时前
Python与Redis集合深度解析
开发语言·redis·笔记·python
龙腾AI白云8 小时前
多源数据融合:把零散信号拼成一致图景
大数据·人工智能·python·机器学习·知识图谱
艾派森9 小时前
深度学习实战-基于VGG19的健康和白化珊瑚图像分类识别模型
人工智能·python·深度学习·分类