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

#问题描述

  • 在学习别人的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"
相关推荐
Smoothcloud润云40 分钟前
PyTorch大模型权重加载与启动耗时优化实战:定位磁盘、内存与显存瓶颈
人工智能·pytorch·python·深度学习·gpu算力
databook1 小时前
从循环到向量化:NumPy提速的7个关键思维
python·数据分析·numpy
棉猴1 小时前
玩游戏学Python1-Python和pgzero库的安装
python·pygame·玩游戏·pgzero·pgzrun
诺伦2 小时前
GEO优化数据实证:78%引用流向官网的机制拆解与小品牌三步管线实战教程 | RiseClaw玄策
python·seo·geo·内容营销·ai搜索
oooost2 小时前
pytorch学习笔记1
python·学习方法
数字融合2 小时前
透明化视频孪生虚实映射一体化融合技术
人工智能·python·数码相机
jack186893 小时前
Lovable.Dev 全栈应用快速落地实战指南
python
华研前沿标杆游学3 小时前
【标杆研学】走进茅台集团|对标学习长期主义与匠心精神
python
GitFun4 小时前
KDJ vs RSI:11年数据实测,金叉死叉输了48个点
python·股票·量化交易
李可以量化4 小时前
从零读懂配对交易(上):从套利本源到配对交易的核心逻辑
python·区块链·量化交易·通达信·qmt