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

#问题描述

  • 在学习别人的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"
相关推荐
tryCbest22 分钟前
Python 爬虫从入门到实战(一):基础篇——从零写出第一个爬虫
开发语言·爬虫·python
无小道26 分钟前
Python语句的特色
python·语句
2601_967980112 小时前
python pytest如何编写测试
python·测试用例·pytest·函数·assert
2601_967980113 小时前
Python中heapq模块的各种用法实例
数据结构·python·算法·应用实例·heapq模块
大胖爱学习_MJ3 小时前
超越向量检索:用 Spring Boot + Neo4j 手搓 GraphRAG 知识图谱记忆
java·后端·python
RobinDevNotes3 小时前
24GB Mac 做数字人:声音放本地,画面租云端
人工智能·python·macos·开发工具
学无止境小袁同学5 小时前
LlamaIndex Workflows 学习
python·llm·tensorflow·llamaindex·agent开发·多agent·workflows
鲸渔5 小时前
【AI Agent系列课程13-Python 基础13】JSON 读写:结构化数据交换基础
开发语言·python·json·ai编程
wuyk55515 小时前
Python办公自动化-第01讲-环境搭建与自动化认知
python·自动化·pyqt
高洁0116 小时前
数字孪生与计算机视觉:让机器看懂现场
人工智能·python·机器学习·transformer·迁移学习