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

#问题描述

  • 在学习别人的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"
相关推荐
c_lb728815 分钟前
最新AI量化提效,交易认知和技术实现要接上
人工智能·python
机汇五金_17 分钟前
钣金外壳定制厂家助力设备升级
大数据·人工智能·python·物联网
xxie12379441 分钟前
Python 闭包的调用方法与实践
开发语言·python
HZZD_HZZD42 分钟前
用电行为异常检测VAE-基于PyTorch设计用电行为异常检测模型:从时序特征提取到变分自编码器部署的完整实战
人工智能·pytorch·python
思-无-涯1 小时前
AI Agent技能编写与质量保障
人工智能·python
2601_956319882 小时前
2026年下半年AI量化学习,分清表达开发和验证
人工智能·python
CTA量化套保2 小时前
最新AI量化效率提升,用示例拆解练习压实路径
人工智能·python
zhiSiBuYu05172 小时前
混合检索实战指南:关键词与向量的完美融合
人工智能·python·机器学习
weixin_413063212 小时前
复现 MatchED 边缘检测模型(单张图片重复8次,训练200 epoch)
python·算法·计算机视觉·边缘检测模型
许彰午2 小时前
74_Python自动化办公之Excel操作
python·自动化·excel