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

#问题描述

  • 在学习别人的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"
相关推荐
名字还没想好☜10 分钟前
用 Python struct 解析二进制协议:pack/unpack、字节序与对齐踩坑
开发语言·python·二进制·struct
青 春 记 忆1 小时前
LeetCode 155. 最小栈|Python 解法详解
开发语言·python·leetcode
程序员三藏10 小时前
Python+requests实现接口自动化测试
自动化测试·软件测试·python·测试工具·职场和发展·测试用例·接口测试
一直走下去-明12 小时前
简单的http抓包解包完整代码
开发语言·python
雷帝木木12 小时前
数据湖与数据仓库:从理论到实践
人工智能·python·深度学习·机器学习
数字化转型分享点滴12 小时前
机加工车间上线 SH‑AIOT 物联网会遇到哪些常见实施难点
python·物联网
05664613 小时前
agent学习——流式响应与文本切分
网络·python·学习
OPEN-F13 小时前
Python进阶教程:正则表达式进阶与文本处理
开发语言·python·正则表达式
新网企兴13 小时前
2026年陕西做GEO推广,找新网企兴解决获客难题
python·搜索引擎
青 春 记 忆13 小时前
LeetCode 142. 环形链表 II|Python 解法详解
python·leetcode·链表