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

#问题描述

  • 在学习别人的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"
相关推荐
逻极11 分钟前
FastAPI 实战:从入门到自动化文档,如何把API开发效率提升200%
python·api·fastapi·swagger·异步
半兽先生42 分钟前
大模型技术开发与应用——5.大模型Agent开发(CrewAI)
大数据·人工智能·python·机器学习·ai
眼泪划过的星空1 小时前
快速了解LangGraph:构建智能Agent工作流的核心框架
人工智能·python·langchain
IsSh9nj6q2 小时前
Python全栈应用搭建神器magic-dash .新版本介绍
开发语言·python·dash
Cachel wood2 小时前
hands-on-modern-rl:动手学强化学习策略梯度reinforce
开发语言·python
蓝斯4972 小时前
一碰即传,重构跨设备文件分享体验
开发语言·python·重构
寒水馨2 小时前
macOS下载、安装uv-0.12.0(附安装包uv-aarch64-apple-darwin.tar.gz)
python·macos·rust·项目管理·包管理器·astral·pip替代
码云骑士3 小时前
85-Prompt是一门工程-结构化分层-System-vs-User-Prompt
python·prompt
qq_22589174663 小时前
基于Python的中药药材数据可视化分析系统
python·机器学习·数据分析·django