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

#问题描述

  • 在学习别人的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"
相关推荐
青 春 记 忆8 分钟前
LeetCode 283. 移动零|Python 解法详解
python·算法·leetcode
人工干智能17 分钟前
科普:Python中的生成器——带`yield`的函数
开发语言·python
whcyhhh18 分钟前
头歌实践教学平台:数据科学与大数据技术导论(十四)
大数据·开发语言·python
清水白石00819 分钟前
Python dataclass 高级避坑指南:从 default_factory、frozen、slots 到哈希灾难
windows·python·哈希算法
在学了加油23 分钟前
阿尔茨海默病诊断(优化特征选择版)
人工智能·python·dnn
淼澄研学32 分钟前
GPT-4o及mini模型参数解析与Python API调用实操
开发语言·python
kyrie_sakura1 小时前
python学习笔记 7--- 文件(IO)操作
笔记·python·学习
Patrick在香港1 小时前
Claude Agent 进阶编排:循环控制 + 写权限审批闸门 + 幂等重试
python·agent·claude·编排·anthropic api
Highcharts.js1 小时前
Highcharts for Python 一套 Python 可视化图表生成库
开发语言·python·highcharts·可视化图表