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

#问题描述

  • 在学习别人的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"
相关推荐
郭老二8 小时前
【Python】基本语法:装饰器语法糖@
python
_Jimmy_9 小时前
Agent常用检索器的详细介绍
python·langchain
小柯南敲键盘9 小时前
图片翻译API接入与自动化实现指南
运维·python·自动化
旅僧10 小时前
Q-learning(自用)
python·机器学习
Python大数据分析@10 小时前
曝梁文锋称「一度不想维护C端用户,奈何赶不走」,DeepSeek真不需要C端用户吗?可能会有啥影响吗?
python
艾斯特_11 小时前
工作流与多Agent协作:LangGraph、MCP和A2A的应用分层
人工智能·python·ai
IT小盘11 小时前
04-大模型流式输出原理-SSE与Python实现
开发语言·网络·人工智能·python
我叫黑大帅11 小时前
add()和 __add__() 写法哪个更好呢?
后端·python·面试
不如语冰12 小时前
AI大模型入门-Python进阶-上下文管理与with语句
开发语言·数据结构·数据库·人工智能·pytorch·redis·python
柠檬味的Cat12 小时前
GEO优化系统哪个渠道商好
大数据·人工智能·python