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

#问题描述

  • 在学习别人的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"
相关推荐
Awesome Baron30 分钟前
skill、tool calling、MCP区别
开发语言·人工智能·python
测试员周周1 小时前
【AI测试系统】第4篇:告别硬编码!基于 Markdown + Python 的 Skill 引擎设计:让 AI 测试系统拥有无限扩展的“灵魂”
人工智能·python·测试
武帝为此1 小时前
【Selenium 屏幕截图】
python·selenium·测试工具
念恒123062 小时前
Python(列表进阶)
python·学习
27669582922 小时前
阿里最新acw_sc__v2 分析
开发语言·python·acw_sc__v2·acw_sc__v2逆向·acw_sc__v2算法·acw_sc__v2算法分析·cookie逆向
vortex53 小时前
python 库劫持:原理、利用与防御
python·网络安全·提权
捉鸭子3 小时前
某音a_bogus vmp逆向
爬虫·python·web安全·node.js·js
曲幽3 小时前
FastAPI 生产环境静态文件完全指南:从 /favicon.ico 404 到 HSTS 混合内容,一次全根治
python·fastapi·web·static·media·404·hsts·favicon·url_for
Dontla3 小时前
Python asyncpg库介绍(基于Python asyncio的PostgreSQL数据库驱动)连接池、SQLAlchemy
数据库·python·postgresql
zh1570234 小时前
如何编写动态SQL存储过程_使用sp_executesql执行灵活查询
jvm·数据库·python