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

#问题描述

  • 在学习别人的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"
相关推荐
sensen_kiss几秒前
Python安装与环境配置全程详细教学(包含Windows版和Mac版)
开发语言·python·pycharm
Dr.Kun5 分钟前
【鲲码园Python】基于yolov11的番茄成熟度检测系统
开发语言·python·yolo
白开水+6 分钟前
AI学习-第二天
python·学习
洛克大航海11 分钟前
Python面向对象
开发语言·python·面向对象
luoluoal12 分钟前
基于python的web渗透测试工具(源码+文档)
python·mysql·django·毕业设计·源码
不会飞的鲨鱼15 分钟前
腾讯录音文件语音识别 python api接口
人工智能·python·语音识别
007php00725 分钟前
mac笔记本中在PHP中调用Java JAR包的指南
java·ide·python·面试·职场和发展·pycharm·php
智航GIS35 分钟前
ArcGIS脚本工具之---左上至右下分组编号
python·arcgis
莫问前路漫漫1 小时前
Python包管理工具pip完整安装教程
开发语言·python
_codemonster1 小时前
手语识别及翻译项目实战系列(四)整体架构
人工智能·python·计算机视觉