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

#问题描述

  • 在学习别人的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"
相关推荐
qq_4523962318 分钟前
第十四篇:《JMeter插件扩展:自定义函数与第三方插件》
开发语言·python·jmeter
m0_7020365344 分钟前
mysql如何导出特定条件的查询数据_使用mysqldump加where参数
jvm·数据库·python
m0_733565461 小时前
bootstrap怎么实现响应式的文章瀑布流布局
jvm·数据库·python
m0_463672202 小时前
Golang如何用火焰图分析性能_Golang火焰图教程【对比】
jvm·数据库·python
knight_9___2 小时前
大模型project面试4
人工智能·python·深度学习·算法·面试·agent
m0_591364732 小时前
Go语言怎么做链路追踪_Go语言分布式链路追踪教程【精选】
jvm·数据库·python
m0_463672202 小时前
HTML函数工具是否支持雷蛇等游戏外设_RGB同步汇总【汇总】
jvm·数据库·python
zkkkkkkkkkkkkk2 小时前
python使用celery实现异步任务
redis·python·rabbitmq·rocketmq
iAm_Ike2 小时前
如何用 IndexedDB 存储从 API 获取的超大列表并实现二级索引
jvm·数据库·python
Land03292 小时前
指纹浏览器自动化集成方案|多浏览器RPA适配实战记录
运维·人工智能·爬虫·python·selenium·自动化·rpa