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

#问题描述

  • 在学习别人的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"
相关推荐
赟爸3 分钟前
直播切片素材杂乱不好复用,易元AI要怎么处理
大数据·人工智能·python
怪奇云呼军41 分钟前
从声音特征到 CRM 回流:闪电智能 Voice Agent 沟通策略自适应系统 v1 实战
android·人工智能·python·音视频·语音识别
jufeng13071 小时前
【系列:手搓自主 AI Agent:Hermes 架构原理剖析 · 第 6 篇】
python·ai agent·记忆系统
kevinnett2 小时前
别再把模型地址写死了:用 Python 设计一个可切换的 LLM 调用层
python
天天进步20152 小时前
Python全栈项目--协同办公平台
开发语言·python
GEOshijie1233 小时前
GEO服务商算法适配承诺怎么验收?48小时响应的合同化考核方案
人工智能·python
卷无止境3 小时前
FastAPI 前端托管全攻略:从静态文件到大型全栈项目架构
后端·python
QQ5416451213 小时前
【驿帮查件助手python开源】开源聚合查件机器人,实现 24 类驿站批量查件取代短信通知。技术方案分享
python·机器人·开源·驿站查件机器人
卷无止境3 小时前
当FastAPI项目开始"膨胀",代码该往哪儿放
后端·python
用户8356290780514 小时前
Python设置PowerPoint幻灯片背景的方法
后端·python