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

#问题描述

  • 在学习别人的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"
相关推荐
2601_9669496526 分钟前
实时行情中的成交量 Volume 到底是什么?包含盘中撤单量吗?从交易数据语义到 QuantDash 实战解析
开发语言·人工智能·python·量化·quantdash·量化数据源
you鬰33 分钟前
datawhale--llm-algo-leetcode9️⃣ SFT Training Loop
python·datawhale
叫我:松哥41 分钟前
基于flask仿小米商城管理系统,使用flask开的一个商场网站
数据库·后端·python·flask
智购科技无人售货机工厂1 小时前
2026自动售货机防拆机物理安全设计:从安全螺丝到结构互锁的工程实践~YH
android·网络·驱动开发·python·单片机·安全·云原生
2401_868534781 小时前
校园网规划与设计
python·pygame
小猴子爱上树1 小时前
跨境电商AI批量图片翻译工具,视频字幕翻译免费试用
人工智能·python·音视频
zx_741484811 小时前
【Python入门】爬虫实战:Requests + XPath 从基础到实战
开发语言·爬虫·python
高洁011 小时前
Teacher Forcing技术解析
人工智能·python·深度学习·transformer·知识图谱
2601_962065251 小时前
从零创建一个 Django 项目
后端·python·django
溪语流沙2 小时前
【Python项目实战】虚拟环境与依赖管理:venv / pip / requirements.txt实操
开发语言·python·pip