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

#问题描述

  • 在学习别人的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"
相关推荐
飞猪~1 小时前
LangChain python 版本 第一集
开发语言·python·langchain
2601_956319881 小时前
最新AI量化提效,先做可验证的小流程
人工智能·python
开飞机的舒克_3 小时前
FastAPI 实战入门:从路由、参数校验到依赖注入的后端开发指南
python·fastapi
霸道流氓气质3 小时前
Kiro 中反编译 JAR 包并分析字节码的流程指南
chrome·python·jar
人工智能时代 准备好了吗4 小时前
AI回答内容进入率监测:引用识别、文本匹配与语义判断
开发语言·人工智能·python
Metaphor6924 小时前
使用 Python 冻结 Excel 文件中的行、列和单元格
开发语言·python·excel
言乐64 小时前
Python实现建造微服务商城后台
开发语言·python·算法·微服务·架构
fenglllle5 小时前
chromadb emmbedding 向量检索
人工智能·python·embedding
cui_ruicheng5 小时前
Python从入门到实战(六):非序列容器
开发语言·python
百里香酚兰5 小时前
【python学习笔记】pyttsx3库疑似只播报一次语音
笔记·python·学习