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

#问题描述

  • 在学习别人的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"
相关推荐
用户83562907805110 分钟前
使用 Python 管理 PDF 属性和元数据
后端·python
猎嘤一号33 分钟前
【2026 最新】Windows 11 右键菜单还原为 Windows 10 经典样式:一条命令、原理、回退与新版说明
windows·python
用户8356290780511 小时前
使用 Python 在 Word 文档中创建自定义图表
后端·python
kyrie_sakura2 小时前
python学习笔记11 -- 进程和线程
笔记·python·学习
Jialu.2 小时前
中文 NLP 模型部署实战:FastAPI 接口 + Streamlit 看板
人工智能·python·自然语言处理·fastapi
Asum1ta3 小时前
K8s 学习环境搭建:Python 与 PyCharm 开发环境配置指南
python·学习·kubernetes
知识汲取者3 小时前
FastAPI 学习教程(写给想学 FastAPI 的 Java 工程师的)
python·学习·fastapi
飞Link4 小时前
动作方法中的分割与过度分割方法全解析(含代码实战与踩坑案例)
人工智能·python·算法·计算机视觉
小鹿的周先生4 小时前
第四章-SpringAI-函数调用&ToolCalling
开发语言·人工智能·python