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

#问题描述

  • 在学习别人的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"
相关推荐
七颗糖很甜7 小时前
电离层对地基雷达测量精度的影响分析与校正方法
python
AC赳赳老秦8 小时前
知识产权辅助:用 OpenClaw 批量生成专利交底书 / 软著申请材料,自动校验格式与内容合规性
java·人工智能·python·算法·elasticsearch·deepseek·openclaw
小熊Coding8 小时前
Python2D射击冒险闯关游戏2.0版本
python·pygame
FYKJ_20109 小时前
springboot校园兼职平台--附源码02041
java·javascript·spring boot·python·eclipse·django·php
yanghuashuiyue10 小时前
Deep Agents 框架-CLI
python·langchain·langgraph·deepagents
Zik----11 小时前
DAEFR (ICLR 2024)— 盲脸超分模型解读
人工智能·python·高光谱图像·光谱恢复
头发够用的程序员11 小时前
C++和Python面试经典算法汇总(一)
开发语言·c++·python·算法·容器·面试
夜猫逐梦11 小时前
【逆向经验】一篇文章讲透为什么CE搜不到Python游戏的内存值
开发语言·python·游戏
Zik----11 小时前
CILP模型讲解
人工智能·python·多模态
陈eaten11 小时前
汇编使用AES指令集实现AES解密
汇编·python·aes解密·aes指令集