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

#问题描述

  • 在学习别人的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"
相关推荐
2401_846339564 小时前
Vue 3 中集成 Three.js 场景的完整实现指南
jvm·数据库·python
落雪寒窗-4 小时前
Python开发个人日常记录
开发语言·python
2301_775639894 小时前
Golang怎么写TODO待办应用_Golang TODO应用教程【深入】
jvm·数据库·python
iuvtsrt4 小时前
WordPress 分页失效的常见原因与正确实现方案
jvm·数据库·python
Resistance丶未来4 小时前
Agency-Agents 多智能体协作系统落地指南
python·大模型·nlp·github·copilot·claude·gemini
yzx9910134 小时前
Python异步编程入门到实践:用asyncio写出高性能代码
python
云天AI实战派4 小时前
Agent 全流程实战:用 Python 搭建技能路由智能体,落地小龙虾门店运营助手
开发语言·人工智能·python
2401_871492855 小时前
C#怎么使用泛型 C#泛型类泛型方法和泛型约束的定义和使用方法【语法】
jvm·数据库·python
我滴老baby5 小时前
工具调用全景解析从Function Calling到MCP协议的完整实践
开发语言·人工智能·python·架构·fastapi
小白学大数据5 小时前
抖音搜索页数据批量爬取,多关键词同步采集实现
爬虫·python·数据分析