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

#问题描述

  • 在学习别人的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"
相关推荐
wertyuytrewm15 分钟前
用Python实现自动化的Web测试(Selenium)
jvm·数据库·python
曲辕RPA28 分钟前
深度解析GEO技术及背后的机器人曲辕RPA
python·ai·自动化·rpa
2301_7644413334 分钟前
使用python构建的STAR实验ΛΛ̄自旋关联完整仿真
开发语言·python·算法
xifangge202540 分钟前
Python 爬虫实战:爬取豆瓣电影 Top250 数据并进行可视化分析
开发语言·爬虫·python
Flittly1 小时前
【从零手写 ClaudeCode:learn-claude-code 项目实战笔记】(10)Team Protocols (团队协议)
笔记·python·ai·ai编程
阿_旭1 小时前
基于YOLO26深度学习的蓝莓成熟度检测与分割系统【python源码+Pyqt5界面+数据集+训练代码】图像分割、人工智能
人工智能·python·深度学习·毕业设计·蓝莓成熟度检测
lxmyzzs1 小时前
使用Python分析COCO数据集标注信息:一个简单脚本实现统计与可视化
python·深度学习·目标检测·计算机视觉
wertyuytrewm1 小时前
自动化与脚本
jvm·数据库·python
qq_417695051 小时前
Python深度学习入门:TensorFlow 2.0/Keras实战
jvm·数据库·python
problc1 小时前
在 OpenClaw 里一句话记账:消费说出来,账单自动进乖猫记账 App
开发语言·python