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

#问题描述

  • 在学习别人的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"
相关推荐
梨落秋霜7 小时前
Python入门篇【文件处理】
android·java·python
Java 码农7 小时前
RabbitMQ集群部署方案及配置指南03
java·python·rabbitmq
张登杰踩9 小时前
VIA标注格式转Labelme标注格式
python
Learner9 小时前
Python数据类型(四):字典
python
odoo中国10 小时前
Odoo 19 模块结构概述
开发语言·python·module·odoo·核心组件·py文件按
Jelena1577958579210 小时前
Java爬虫api接口测试
python
踩坑记录11 小时前
leetcode hot100 3.无重复字符的最长子串 medium 滑动窗口(双指针)
python·leetcode
诸神缄默不语12 小时前
Python处理Word文档完全指南:从基础到进阶
python
海棠AI实验室13 小时前
第四章 项目目录结构:src/、configs/、data/、tests/ 的黄金布局
python·项目目录结构
爱笑的眼睛1114 小时前
超越可视化:降维算法组件的深度解析与工程实践
java·人工智能·python·ai