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

#问题描述

  • 在学习别人的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"
相关推荐
2501_948122638 分钟前
Qs 跨端三方库仓颉适配全流程
python·react native·django·tornado
萌动的小火苗11 分钟前
MQTT的QoS0、QoS1、QoS2有什么区别?
开发语言·网络·python·php·信息与通信
forest_0912 分钟前
《大模型原理通俗讲》系列 00|开篇 大模型到底是怎么回事
人工智能·python·prompt·agi
工程师迪菲18 分钟前
【基础篇 01】YOLO 到底在做什么?先从一张图片看明白
python
happylifetree40 分钟前
Python72:核心语法-类型注解-函数的类型注解
python
liudachu1 小时前
Agent 开发常见名词说明与类比
python·langchain
devilnumber1 小时前
Lambda 表达式(Java)优缺点清晰分析
java·开发语言·python
大泽九章1 小时前
XSS入门:存储型、反射型、DOM型,用Flask全复现
python·网络安全·flask
class心平气和1 小时前
ADB 工具函数 Python 使用教程
开发语言·python·adb
小小张说故事2 小时前
Python 里 is 和 == 到底差在哪?拆开小整数池、字符串驻留与 0ns 身份比较
python