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

#问题描述

  • 在学习别人的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"
相关推荐
独行soc22 分钟前
2025年渗透测试面试题总结-258(题目+回答)
网络·python·安全·web安全·渗透测试·安全狮
程序员小远1 小时前
Appium-移动端自动测试框架详解
自动化测试·软件测试·python·测试工具·职场和发展·appium·测试用例
青瓷程序设计1 小时前
花朵识别系统【最新版】Python+TensorFlow+Vue3+Django+人工智能+深度学习+卷积神经网络算法
人工智能·python·深度学习
hyswl6661 小时前
2025年郑州开发小程序公司推荐
python·小程序
B站计算机毕业设计之家1 小时前
基于Python音乐推荐系统 数据分析可视化 协同过滤推荐算法 大数据(全套源码+文档)建议收藏✅
python·数据分析·推荐算法
用户785127814702 小时前
实战解析:淘宝/天猫商品描述API(taobao.item_get_desc)接口
python
codists2 小时前
Pycharm错误:JetBrains AI URL resolution failure
python
青瓷程序设计2 小时前
鱼类识别系统【最新版】Python+TensorFlow+Vue3+Django+人工智能+深度学习+卷积神经网络算法
人工智能·python·深度学习
该用户已不存在3 小时前
Python正在死去,2026年Python还值得学吗?
后端·python
战南诚3 小时前
flask之“应用上下文,请求上下文”
python·flask