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

#问题描述

  • 在学习别人的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"
相关推荐
2301_7644413333 分钟前
Python管理咨询数据可视化实战:收入分布与顾问利用率双轴对比图表生成脚本
开发语言·python·信息可视化
该用户已不存在1 小时前
不知道这些工具,难怪的你的Python开发那么慢丨Python 开发必备的6大工具
前端·后端·python
Monkey的自我迭代2 小时前
Python标准库:时间与随机数全解析
前端·python·数据挖掘
SsummerC2 小时前
【leetcode100】下一个排列
python·算法·leetcode
Kelaru2 小时前
本地Qwen中医问诊小程序系统开发
python·ai·小程序·flask·project
Menger_Wen3 小时前
分析新旧因子相关性
python·机器学习·区块链
RAY_01044 小时前
Python—数据容器
开发语言·python
June bug4 小时前
【python基础】python和pycharm的下载与安装
开发语言·python·pycharm
im_AMBER5 小时前
python实践思路(草拟计划+方法)
开发语言·python
站大爷IP5 小时前
Python与JSON:结构化数据的存储艺术
python