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

#问题描述

  • 在学习别人的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"
相关推荐
SsummerC12 分钟前
【leetcode100】下一个排列
python·算法·leetcode
Kelaru35 分钟前
本地Qwen中医问诊小程序系统开发
python·ai·小程序·flask·project
Menger_Wen36 分钟前
分析新旧因子相关性
python·机器学习·区块链
RAY_01042 小时前
Python—数据容器
开发语言·python
June bug2 小时前
【python基础】python和pycharm的下载与安装
开发语言·python·pycharm
im_AMBER3 小时前
python实践思路(草拟计划+方法)
开发语言·python
站大爷IP3 小时前
Python与JSON:结构化数据的存储艺术
python
大菠萝学姐3 小时前
基于Spring Boot和Vue的高校图书馆座位预约系统的设计与实现
java·vue.js·spring boot·后端·python·mysql·vue
Tomorrow'sThinker3 小时前
[特殊字符] Python 批量生成词云:读取词频 Excel + 自定义背景 + Excel to.png 流程解析
python·excel
野指针121384 小时前
【使用Flask基于PaddleOCR3.0开发一个接口 调用时报错RuntimeError: std::exception】
python·flask