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

#问题描述

  • 在学习别人的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"
相关推荐
love530love几秒前
Flash Attention 2.8.3 在 Windows + RTX 3090 上成功编译与运行复盘笔记(2026年1月版)
人工智能·windows·笔记·python·flash_attn·flash attention·z-image
@zulnger7 分钟前
python 学习笔记(异常对象)
笔记·python·学习
No0d1es12 分钟前
2025年12月 GESP CCF编程能力等级认证Python七级真题
python·青少年编程·gesp·ccf
Hello.Reader13 分钟前
PyFlink Table API Data Types DataType 是什么、UDF 类型声明怎么写、Python / Pandas 类型映射一文搞懂
python·php·pandas
嫂子的姐夫14 分钟前
013-webpack:新东方
爬虫·python·webpack·node.js·逆向
CCPC不拿奖不改名15 分钟前
python基础:python语言的数据结构+面试习题
开发语言·数据结构·python·面试
eybk16 分钟前
拖放pdf转化为txt文件多进程多线程合并分词版
java·python·pdf
APIshop21 分钟前
Python 爬虫获取「item_video」——淘宝商品主图视频全流程拆解
爬虫·python·音视频
数据大魔方22 分钟前
【期货量化实战】威廉指标(WR)策略:精准捕捉超买超卖信号(Python源码)
开发语言·数据库·python·算法·github·程序员创富
天天睡大觉23 分钟前
Python学习6
windows·python·学习