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

#问题描述

  • 在学习别人的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"
相关推荐
apcipot_rain13 小时前
Python实战——蒙特卡洛模拟分析杀牌游戏技能收益
python·游戏·数学建模
老绿光13 小时前
Python 字典完全指南:从入门到实战
linux·服务器·python
是小蟹呀^13 小时前
【总结】LangChain中如何维持记忆
python·langchain·memory
蓝色的杯子13 小时前
OpenClaw一文详细了解-手搓OpenClaw-4 Tool Runtime
人工智能·python
克里普crirp13 小时前
电离层TEC地图中添加晨昏线/昼夜转换线
python
Dxy123931021614 小时前
Python使用PyEnchant详解:打造高效拼写检查工具
开发语言·python
架构师老Y14 小时前
011、消息队列应用:RabbitMQ、Kafka与Celery
python·架构·kafka·rabbitmq·ruby
枫叶林FYL14 小时前
【Python高级工程与架构实战】项目四:生产级LLM Agent框架:基于PydanticAI的类型安全企业级实现
人工智能·python·自然语言处理
龙腾AI白云14 小时前
多模大模型应用实战:智能问答系统开发
python·机器学习·数据分析·django·tornado
Hommy8814 小时前
【开源剪映小助手】配置与部署
python·开源·aigc·剪映小助手