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

#问题描述

  • 在学习别人的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"
相关推荐
Shorasul2 分钟前
golang如何实现设备数据采集网关_golang设备数据采集网关实现要点
jvm·数据库·python
慕涯AI6 分钟前
Agent 30 课程开发指南 - 第19课
人工智能·python
2301_764150567 分钟前
如何用 some 检测数组中是否存在至少一个满足条件的项
jvm·数据库·python
我是无敌小恐龙14 分钟前
线下班第一课
python·考研·django·ai编程
_oP_i16 分钟前
python 之playwright 介绍
开发语言·python
@不误正业23 分钟前
大模型注意力机制源码解析-从MQA到MLA全链路演进与PyTorch实现
人工智能·pytorch·python
weixin_4087177723 分钟前
CSS如何优化大型项目样式_使用SASS预处理器提升开发效率
jvm·数据库·python
2301_8135995527 分钟前
CSS如何解决CSS引入后的样式覆盖_理解优先级原则避免重写
jvm·数据库·python
Li emily38 分钟前
外汇api接口实践:实时汇率与历史数据获取
人工智能·python·api·fastapi
weixin_4087177743 分钟前
PHP8.1新特性对AI开发帮助_JIT编译优势【解答】
jvm·数据库·python