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

#问题描述

  • 在学习别人的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"
相关推荐
SeatuneWrite43 分钟前
动态漫软件2026推荐,助力高效创作体验
人工智能·python
AC赳赳老秦1 小时前
文案策划提效:OpenClaw批量生成活动文案、宣传海报配文,适配不同渠道调性
java·大数据·服务器·人工智能·python·deepseek·openclaw
甄心爱学习1 小时前
【项目实训】法律文书智能摘要系统5
python·github
烟雨江南aabb1 小时前
Python第四弹:python进阶-匿名函数和内置函数
开发语言·python
TE-茶叶蛋1 小时前
Java 8 引入的Stream API-stream()
java·windows·python
小陈的进阶之路1 小时前
Python系列课(9)——面向对象
开发语言·python
wen_zhufeng2 小时前
python-dotenv 使用文档
数据库·python·oracle
Str_Null2 小时前
杀戮尖塔通过修改记录文件和备份文件进行修改血量和金币
python
钝挫力PROGRAMER2 小时前
复杂PDF转Markdown实战:从Marker到多模态的处理全记录
python·pdf
TechWayfarer2 小时前
账号安全实战:基于IP归属地基线的三原则异地登录风控模型
服务器·网络·python·安全·网络安全