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

#问题描述

  • 在学习别人的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"
相关推荐
大模型码小白6 小时前
【Python零基础教程】继承、多态与魔法函数:面向对象编程三大核心特性详解
java·大数据·开发语言·人工智能·python·ai编程
麻雀飞吧6 小时前
最新量化学习路径,交易认知和技术实现要并行
人工智能·python
C^h10 小时前
python函数学习
人工智能·python·机器学习
Fanta丶10 小时前
4.Python set()集合、dict(字典、映射)、 数据容器的通用功能
python
决战灬10 小时前
langgraph之interrupt(理论篇)
人工智能·python·agent
兜客互动11 小时前
2026年AI关键词拓展挖掘软件,高效助力内容创作精准获流
人工智能·python
weixin_5386019711 小时前
智能体测开Day30pytest测试框架
python
MC皮蛋侠客11 小时前
uv 系列(七):CI/CD、Docker 与私有索引——生产级交付
python·ci/cd·docker·uv
邪神与厨二病11 小时前
牛客周赛 Round 153
python·算法
yaoxin52112311 小时前
470. Java 反射 - Member 接口与 AccessFlag
java·开发语言·python