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

#问题描述

  • 在学习别人的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"
相关推荐
 梦晓天明1 小时前
12.集合介绍以及数组的使用选择
linux·开发语言·python
嵌入式-老费2 小时前
Easyx图形库应用(python+opencv的图形库开发)
开发语言·python·opencv
m0_64880493_江哥2 小时前
Python实现随机选播视频的示例代码
前端·python·音视频
sunshine~~~2 小时前
【笔记】macOs arm架构安装虚拟机Ubuntu环境:ROS2 + Python开发
arm开发·笔记·python·macos·ros2
云和数据.ChenGuang3 小时前
tensorflow的广播机制
人工智能·python·tensorflow
咕白m6253 小时前
使用 Python 轻松实现 Excel 转 PDF 全指南
python
CodeCraft Studio3 小时前
MPP文件处理组件Aspose.Tasks教程:使用Python在Excel中打开MPP文件
python·ui·excel·csv·mpp·aspose·ms project
王六岁3 小时前
🐍 前端开发 0 基础学 Python 入门指南:f-strings 篇
前端·javascript·python
清空mega3 小时前
从零开始搭建 flask 博客(1)实验
后端·python·flask