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

#问题描述

  • 在学习别人的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"
相关推荐
workflower5 小时前
时序数据获取事件
开发语言·人工智能·python·深度学习·机器学习·结对编程
C++业余爱好者6 小时前
Java 提供了8种基本数据类型及封装类型介绍
java·开发语言·python
AI Echoes7 小时前
构建一个LangChain RAG应用
数据库·python·langchain·prompt·agent
派大鑫wink8 小时前
从零到精通:Python 系统学习指南(附实战与资源)
开发语言·python
c骑着乌龟追兔子8 小时前
Day 38 官方文档的阅读
python
羸弱的穷酸书生8 小时前
国网 i1协议 python实现
开发语言·python
weixin_462022358 小时前
RAW-Adapter: Adapting Pre-trained Visual Model to Camera RAW Images
python·计算机视觉
电子硬件笔记8 小时前
Python语言编程导论第三章 编写程序
开发语言·python·编辑器
布谷歌8 小时前
在java中实现c#的int.TryParse方法
java·开发语言·python·c#