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

#问题描述

  • 在学习别人的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"
相关推荐
用户70887690393812 小时前
给传统 SaaS 增加 AI 能力:3个真实落地场景
python
卷无止境12 小时前
FastAPI中间件全解析:请求处理链条上的隐形关卡
后端·python·fastapi
用户03321266636712 小时前
使用 Python 将 HTML 内容添加到 PowerPoint 演示文稿中
python·html
看浪的路人12 小时前
第4讲:MCP Client 开发——连接、发现、调用
windows·python·ai
Swift社区12 小时前
Python 开发环境怎么选?PyCharm、VS Code、Trae 谁更适合 AI 开发?
人工智能·python·pycharm
卷无止境12 小时前
聊聊Web开发里的流式数据 从原理到FastAPI实战
后端·python·fastapi
SMF191912 小时前
【PyCharm】让 PyCharm 使用 .venv 虚拟环境
ide·python·pycharm
修远客13 小时前
感知模块:Agent的眼睛和耳朵 — 三层降级策略让Agent永不"失明"
python·agent
circuitsosk13 小时前
Prompt Engineering进阶:面向复杂业务场景的模板化管理与动态注入策略
python·langchain·prompt·跨境电商·rag·上下文管理·动态注入
Livia要学习13 小时前
Python闭包
开发语言·jvm·python