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

#问题描述

  • 在学习别人的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"
相关推荐
benchmark_cc7 分钟前
个人量化系统搭建:如何利用 QuantDash 实现 A 股日 K 线前复权数据的高效获取与质量校验?
python·数据分析·pandas·量化交易·股票数据·quantdash
hhb_61814 分钟前
Python异步队列实战:高效处理耗时任务
开发语言·python
2601_9628857218 分钟前
一个接口取 A 股+美股+港股:多市场数据方案对比
python
SEO_juper25 分钟前
Node.js 全站死链检测工具:从 sitemap 出发一次找全 404
开发语言·人工智能·python·node.js·seo·外贸独立站
ljt272496066129 分钟前
Python笔记(九)--asyncio
笔记·python
老孟说禅38 分钟前
自动化测试实战(二)
python
2601_9679873743 分钟前
你们都用Python实现了哪些自动化办公?
python·excel·自动化办公·1024程序员节·学习资料·跨平台操作
wflynn44 分钟前
GitHub 今日推荐|Snapintosh:用 ARM EL2 监控器骗过内核,让骁龙芯片笔记本跑 macOS
python·开源·github
happylifetree1 小时前
Python69:核心语法-函数进阶-案例1(递归)
python
外收内放1 小时前
FastAPI猜字谜实战(3):把每一局存成JSON
开发语言·python·学习·json·fastapi