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

#问题描述

  • 在学习别人的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"
相关推荐
AAD5558889917 分钟前
基于Faster RCNN的暴力行为检测模型优化与实现_1
python
难得的我们23 分钟前
超越Python:下一步该学什么编程语言?
jvm·数据库·python
工程师老罗27 分钟前
Turtle库的用法
python
Sivan_Xin32 分钟前
拒绝 If-Else 屎山:利用适配器模式(Adapter)构建第三方登录的“防腐层”实战
linux·python·适配器模式
AI Echoes1 小时前
LangChain Runnable组件重试与回退机制降低程序错误率
人工智能·python·langchain·prompt·agent
AAD555888991 小时前
YOLO11-Seg+ContextGuided:智能交通流量估算与拥堵检测实战指南
python
rose and war2 小时前
python和jinja版本问题导致的访问报500
python·ios
小鸡吃米…2 小时前
机器学习 - 感知机(Perceptron)
人工智能·python·机器学习
毅炼2 小时前
Java 基础常见问题总结(1)
开发语言·python
风栖柳白杨2 小时前
【语音识别】Qwen3-ASR原理及部署
人工智能·python·语音识别·xcode·audiolm