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

#问题描述

  • 在学习别人的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"
相关推荐
rgb2gray1 小时前
论文详解 | TWScan:基于收紧窗口的增强扫描统计,实现不规则形状空间热点精准检测
网络·人工智能·python·pandas·交通安全·出租车
小鸡吃米…1 小时前
Python线程同步
开发语言·数据结构·python
清水白石0081 小时前
Python 弱引用深度解析——让缓存不再成为内存泄漏的温床
java·python·缓存
zzb15801 小时前
RAG from Scratch-优化-routing
java·前端·网络·人工智能·后端·python·mybatis
sea12161 小时前
Flask配置MySQL连接信息的最佳实践
python·mysql·flask
XW01059991 小时前
5-6统计工龄
数据结构·python·算法
酱紫学Java1 小时前
数据安全比赛:Python 内置函数实战指南
后端·python·网络安全
廿一夏1 小时前
数据存储容器
python
SNWCC1 小时前
autodl_M000_pytorch
人工智能·pytorch·python
deephub2 小时前
多智能体系统的三种编排模式:Supervisor、Pipeline 与 Swarm
人工智能·python·大语言模型·agent