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

#问题描述

  • 在学习别人的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"
相关推荐
顾林海9 分钟前
Agent入门阶段-编程基础-Python:Python 开发环境与运行方式
python·agent·ai编程
叫我:松哥10 分钟前
基于深度卷积神经网络的水果图片分类算法设计与实现,有ResNet50的迁移学习模型,准确率达95%
人工智能·python·神经网络·机器学习·分类·cnn·迁移学习
Orchestrator_me22 分钟前
Python pip install报SSL错误
python·ssl·pip
开源量化GO23 分钟前
期货 K 线算信号 tick 级止损:天勤双序列 wait_update 触发规则
linux·运维·服务器·python
聆春烟雨簌簌31 分钟前
LangChain4j使用文档
开发语言·python
belong_my_offer1 小时前
在Pycharm中安装conda的保姆级教学
python
CTA终结者1 小时前
期货量化合约代码写错:天勤 symbol 格式与 silent 订阅坑
python·区块链
c_lb72881 小时前
期货程序化撤单改价后仓位乱了:cancel_order 与 TargetPosTask 协作
python
如烟花的信页1 小时前
加速乐cookie逆向分析
javascript·爬虫·python·js逆向
装不满的克莱因瓶1 小时前
PyTorch 与它的自动微分工具:Autograd
人工智能·pytorch·python·深度学习·神经网络·机器学习·ai