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

#问题描述

  • 在学习别人的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"
相关推荐
winfredzhang17 分钟前
用 Python + wxPython 做一个个人健康饮食管理工具:从记录三餐到综合生活建议
python·wxpython·deepseek·生活习惯管理
Irissgwe28 分钟前
十、LangGraph能力详解:工作流的常见模式
python·langchain·ai编程·工作流·langgraph
Merlyn1040 分钟前
【栈】155. 最小栈
python·算法
SilentSamsara43 分钟前
NumPy 进阶:广播机制、ufunc 与向量化计算的工程实践
开发语言·python·青少年编程·性能优化·numpy
林爷万福1 小时前
机器学习在光谱分析中的应用:Python实现
人工智能·python·机器学习
编程探索者小陈1 小时前
接口自动化三件套:JSON Schema 校验 + logging 日志 + Allure 测试报告
开发语言·python
godspeed_lucip1 小时前
LLM和Agent——专题6:Multi Agent 入门(3)
人工智能·python
如此这般英俊1 小时前
手搓Claude Code-第二章 tool_use
人工智能·python·ai·语言模型
geminigoth1 小时前
python入门三:字典、输入、while循环
开发语言·python
Irissgwe2 小时前
十、LangGraph能力详解:LangGraph 的其他特性
python·ai·langchain·langgraph