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

#问题描述

  • 在学习别人的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"
相关推荐
李可以量化4 小时前
Redis Client 从了解到精通(六):redis-py 服务控制与状态监控辅助函数详解
python
李可以量化4 小时前
Redis Client 从了解到精通(六)下:redis-py 时间、库管理与持久化辅助函数详解
python
晓窗科技4 小时前
AI基座哪家好
大数据·人工智能·python
麻雀飞吧4 小时前
学量化:看到“近期工具推荐”时,先问工具要解决什么问题
人工智能·python
jayson.h5 小时前
python——pdf编辑
前端·python·pdf
聪明蛋子哟5 小时前
多智能体协作的三种模式:从群聊到分层,如何设计可扩展的Agent系统
后端·python·flask
zlwool5 小时前
图纸管理选型:从变更频率到齐套率
java·前端·python·erp·设备erp·非标机械
一晌小贪欢6 小时前
python-第15天:Python 列表推导式
开发语言·python·excel·数据可视化·python办公
逗脑IDE6 小时前
零基础学ESP32:光敏传感器——让ESP32拥有“感光”能力!
python·物联网·esp32·智能家居
Java后端的Ai之路6 小时前
17、Python - 观察者模式
开发语言·人工智能·python·观察者模式·外观模式