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

#问题描述

  • 在学习别人的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"
相关推荐
这个人懒得名字都没写19 分钟前
Flask + PyArmor Gunicorn启动报错:RuntimeError: unauthorised use of script
python·flask·gunicorn·pyarmor
C++、Java和Python的菜鸟24 分钟前
第10章 后端Web进阶(Maven高级)
开发语言·python
暗黑小白39 分钟前
路由策略与引擎可替换性
后端·python·ai agent
小罗水1 小时前
第 20 章 高级 RAG 技术与检索优化
人工智能·python·机器学习
bamb001 小时前
一个项目带你入门AI应用开发06
python
liwulin05061 小时前
【ESP32S3】调用百度云语音合成接口后重启
python
m沐沐2 小时前
【机器学习】矿物识别系统实战——六种填充方法×六种模型全面对比
人工智能·python·深度学习·机器学习·矿物识别
软糖姐姐2 小时前
Python:__closure__ 详解
python·闭包·__closure__·自由变量·cell对象
月光船幽幽2 小时前
四层公理框架驱动AI健康诊断
人工智能·python·科技·算法·安全
郝学胜-神的一滴2 小时前
力扣 692:巧用小顶堆高效求解前K个高频单词
java·数据结构·python·程序人生·算法·leetcode·职场和发展