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

#问题描述

  • 在学习别人的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"
相关推荐
quikai19814 小时前
python练习第二组
开发语言·python
熊猫_豆豆5 小时前
python 用手势控制程序窗口文字大小
python·手势识别
测试秃头怪5 小时前
2026最新软件测试面试八股文(含答案+文档)
自动化测试·软件测试·python·功能测试·测试工具·面试·职场和发展
LUU_795 小时前
Day29 异常处理
python
子夜江寒5 小时前
Python 学习-Day8-执行其他应用程序
python·学习
背心2块钱包邮6 小时前
第7节——积分技巧(Integration Techniques)-代换积分法
人工智能·python·深度学习·matplotlib
一个散步者的梦6 小时前
一键生成数据分析报告:Python的ydata-profiling模块(汉化)
python·数据挖掘·数据分析
黑客思维者6 小时前
Python大规模数据处理OOM突围:从迭代器原理到TB级文件实战优化
开发语言·python·github·迭代器·oom
weixin_421133417 小时前
应用日志监控
python
CHANG_THE_WORLD8 小时前
Python 学习三 Python字符串拼接详解
开发语言·python·学习