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

#问题描述

  • 在学习别人的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"
相关推荐
玩大数据的龙威13 小时前
农经权二轮延包—批量替换签名盖章页扫描页
python
AI视觉网奇14 小时前
手部检测 yolov5 实战笔记
python·深度学习·计算机视觉
WXG101114 小时前
【Flask-7】前后端数据交互
python·ios·flask
hyswl66614 小时前
数字货物搬家小程序
python·小程序
LDG_AGI14 小时前
【推荐系统】深度学习训练框架(六):PyTorch DDP(DistributedDataParallel)数据并行分布式深度学习原理
人工智能·pytorch·分布式·python·深度学习·算法·spark
背心2块钱包邮14 小时前
第24节——手搓一个“ChatGPT”
人工智能·python·深度学习·自然语言处理·transformer
执笔论英雄14 小时前
【大模型推理】小白教程:vllm 异步接口
前端·数据库·python
databook14 小时前
Manim v0.19.1 发布啦!三大新特性让动画制作更丝滑
后端·python·动效
8***235514 小时前
SQL Server2022版+SSMS安装教程(保姆级)
后端·python·flask
Sally_xy14 小时前
Python 虚拟环境
开发语言·chrome·python