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

#问题描述

  • 在学习别人的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"
相关推荐
大飞记Python22 分钟前
【2026更新】Python基础学习指南(AI版)——04数据类型
开发语言·人工智能·python
Hello eveybody2 小时前
介绍一下背包DP(Python)
开发语言·python·动态规划·dp·背包dp
2301_795099742 小时前
让 CSS Grid 自适应容器尺寸的动态布局方案
jvm·数据库·python
呆萌的代Ma2 小时前
python读取并加载.env的配置文件
python
Muyuan19982 小时前
27.RAG 系统中的上下文充分性判断:从 Chunk 数量、FAISS 距离到 LLM Relevance Gate
python·django·pdf·fastapi·faiss
U盘失踪了3 小时前
python curl转python脚本
开发语言·chrome·python
FQNmxDG4S3 小时前
Java泛型编程:类型擦除与泛型方法的应用场景
java·开发语言·python
bzmK1DTbd3 小时前
JDBC编程规范:PreparedStatement与事务管理
数据库·python·eclipse
我星期八休息3 小时前
IT疑难杂症诊疗室:AI时代工程师Superpowers进化论
linux·开发语言·数据结构·人工智能·python·散列表
代码小书生3 小时前
math,一个基础的 Python 库!
人工智能·python·算法