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

#问题描述

  • 在学习别人的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"
相关推荐
love530love4 小时前
OpenClaw Windows Companion 桌面客户端 连接 LM Studio 完整配置指南
人工智能·windows·python·openclaw
cui_ruicheng6 小时前
Python从入门到实战(十六):多进程编程
开发语言·python
_Jimmy_7 小时前
FastAPI + SQLAlchemy全局事务管理
python·fastapi
用户8356290780518 小时前
如何使用 Python 在 Excel 中添加、编辑和删除超链接
后端·python
AC赳赳老秦9 小时前
企业工商公开信息采集分析:OpenClaw 批量查询企业工商信息,生成企业画像报告
大数据·开发语言·python·自动化·php·deepseek·openclaw
FoldWinCard10 小时前
D6 Python 基础语法 --- 保留关键字
开发语言·python
暮暮祈安10 小时前
Celery 新手入门指南
java·数据库·python·flask·httpx
JustNow_Man11 小时前
每日高频场景英文口语
python
风吹心凉11 小时前
python3基础2026.7.22
开发语言·python
小猴子爱上树12 小时前
一站式解决图片视频翻译难题的高效AI工具
人工智能·python·音视频