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

#问题描述

  • 在学习别人的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"
相关推荐
麻辣清汤27 分钟前
结合BI多维度异常分析(日期-> 商家/渠道->日期(商家/渠道))
数据库·python·sql·finebi
钢铁男儿37 分钟前
Python 正则表达式(正则表达式和Python 语言)
python·mysql·正则表达式
钢铁男儿1 小时前
Python 正则表达式实战:解析系统登录与进程信息
开发语言·python·正则表达式
前端小趴菜051 小时前
python - range
python
☺����1 小时前
实现自己的AI视频监控系统-第一章-视频拉流与解码1
人工智能·python·音视频
前端小趴菜052 小时前
python - 元组常用操作
python
前端小趴菜052 小时前
python - 列表方法
python
前端小趴菜052 小时前
组合数据类型
python
Kan先生2 小时前
对象存储解决方案:MinIO 的架构与代码实战
数据库·python
秋难降2 小时前
别再用暴力排序了!大小顶堆让「取极值」效率飙升至 O (log n)
python·算法·排序算法