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

#问题描述

  • 在学习别人的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"
相关推荐
全栈凯哥6 分钟前
18.Python中的导入类完全指南
python
sunwenjian88630 分钟前
Java进阶——IO 流
java·开发语言·python
guts3501 小时前
图像篡改数据集下载:COVERAGE、CASIA
python·数据集
森林猿1 小时前
java-modbus-读取-modbus4j
java·网络·python
2401_879693871 小时前
将Python Web应用部署到服务器(Docker + Nginx)
jvm·数据库·python
chushiyunen2 小时前
python chatTts实现tts文本转语音、音频
python
FreakStudio2 小时前
把 Flask 搬进 ESP32,高中生自研嵌入式 Web 框架 MicroFlask !
python·单片机·嵌入式·cortex-m3·异步编程·电子diy
love530love3 小时前
OpenClaw 手机直连配置全流程
人工智能·windows·python·智能手机·c#·agent·openclaw
chushiyunen3 小时前
python中的内置属性 todo
开发语言·javascript·python
2301_793804693 小时前
Python数据库操作:SQLAlchemy ORM指南
jvm·数据库·python