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

#问题描述

  • 在学习别人的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"
相关推荐
APIshop18 分钟前
俄罗斯电商 Ozon 平台:ozon.item_get 商品详情接口深度技术解析
python
m0_7407963630 分钟前
golang如何实现工作流引擎_golang工作流引擎实现要点
jvm·数据库·python
zhaoyong2221 小时前
CSS如何利用Less构建高度自定义组件_通过样式作用域防止冲突与溢出
jvm·数据库·python
2301_781571421 小时前
Less如何优化CSS文件大小_利用压缩配置去除冗余样式
jvm·数据库·python
2401_867623981 小时前
Next.js 13 中为嵌套客户端组件实现局部加载状态的正确方法
jvm·数据库·python
gCode Teacher 格码致知1 小时前
Python教学:正则表达式中的match 和fullmatch的经典使用-由Deepseek产生
python·正则表达式
hnxaoli1 小时前
win10小程序(二十)循环键鼠操作程序
python
Gerardisite1 小时前
CRM、ERP、OA 如何连接企业微信?QiWe 提供标准化解决方案
java·python·机器人·自动化·企业微信