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

#问题描述

  • 在学习别人的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"
相关推荐
谢尔登40 分钟前
分享一些我常用的Skill
java·人工智能·python·actionscript
k4m7v2pz1 小时前
macOS 解压 40GB 分卷+中文密码固件镜像的五个深坑与解决方案
python·7-zip·aes加密·踩坑记录·r36s·多卷zip解压
小白学大数据1 小时前
Python 爬虫实战:抓取汽车之家二手车成交价格与里程数据
开发语言·爬虫·python·汽车
Jazz_z2 小时前
如何用Python将彩色PDF一键转为黑白(灰度)
java·python·pdf
SEO_juper2 小时前
2026年Schema自动注入实战:用Python批量给1000个页面加上JSON-LD,AI引用率实测提升38%
人工智能·python·json·seo·独立站
zzzll11112 小时前
HashMap、HashTable、ConcurrentHashMap 详细区别与深度解析
开发语言·python
程序员AI工坊2 小时前
Agent 开发:ReAct 循环与工具调用实战——从单次调用到自主 Agent
人工智能·后端·python·langchain·agent·react
️学习的小王3 小时前
基于UDP实现简易聊天室(基础版)——Python实现
网络·python·udp
W_326003 小时前
Python 组合数据类型——序列(列表 & 元组)
开发语言·python
二进制杯莫停3 小时前
A和B环境的python版本相同,B环境无法安装pip依赖,离线安装
开发语言·python·pip