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

#问题描述

  • 在学习别人的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"
相关推荐
玉鸯几秒前
多 Agent 并行时如何保证状态一致性?
分布式·python·agent
aGdF8E3gQ20 分钟前
【Application Insights】采样率对Function App日志收集的影响和解决方法
python·flask·wpf
ATMQuant29 分钟前
以AI量化为生:25.vnpy 4.4升级实战 - 魔改版框架如何安全跟进上游
人工智能·python·量化交易·vnpy
卷无止境2 小时前
拯救乱码方块:pandas 绘图中文字体的一揽子解决方案
后端·python
李昊哲小课2 小时前
fastapi sse websocket 智能家居实时控制台
python·websocket·智能家居·fastapi·sse
杰佛史彦明 本王是暴君2 小时前
PyTorch KernelAgent 源码解读 ---(2)--- 总体流程
人工智能·pytorch·python
Zane19942 小时前
别再手写 try/finally 了:一文讲透 with 语句背后的上下文管理器协议
后端·python
李可以量化2 小时前
量化高性能服务框架 Tornado 全面解析(上):异步非阻塞的核心能力与场景落地
大数据·python·量化交易·tornado·qmt·ptrade
内蒙深海大鲨鱼3 小时前
3.Introduction to PyTorch YouTube Series--Autograd
人工智能·pytorch·python
用户0332126663673 小时前
使用 Python 在 Excel 中添加或删除批注
python·excel