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

#问题描述

  • 在学习别人的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"
相关推荐
zh路西法16 分钟前
【ResNet18】从图像到视觉特征:卷积神经网络如何理解图像
pytorch·python·神经网络·cnn·resnet·resnet18
外收内放37 分钟前
Python基础语法练习题(40-42)
开发语言·python
m0_547486661 小时前
《数据挖掘:理论、方法与实践基于Python语言》全套PPT课件2026(中国地质大学)
人工智能·python·数据挖掘
meiying88381 小时前
电商图片批量处理实战:Python+Pillow 一键完成裁剪、压缩、水印与格式转换
python·pillow
高洁011 小时前
AI视频生成技术:从静态图文到动态视觉的内容智能革命
python·深度学习·django·transformer·tornado
沐欣工作室_lvyiyi1 小时前
基于Flask的旅游大数据分析与可视化系统(论文+源码)
python·flask·旅游
施棠海1 小时前
多 Agent 团队编排系统的设计与实测:agent-workflow
python·ai·架构
asdzx671 小时前
Python 实现从 URL 在线下载 PDF 文档教程
python·pdf
Bruce_Liuxiaowei1 小时前
元组与具名元组:把「第 3 个字段」变成「price」
数据结构·python·语法·元组