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

#问题描述

  • 在学习别人的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"
相关推荐
写代码的【黑咖啡】16 分钟前
深入了解 Python 中的 Scrapy:强大的网络爬虫框架
爬虫·python·scrapy
沈浩(种子思维作者)19 分钟前
量子计算真的需要量子硬件吗?谷歌量子计算机真的是未来计算方向吗?你们相信道AI还是豆包?
人工智能·python·量子计算
电化学仪器白超19 分钟前
计量室自动化系统技术文档编制与动态更新说明
运维·python·嵌入式硬件·自动化
信码由缰24 分钟前
SJF4J 五分钟入门:Java 的实用 JSON 门面
java·python·json
@zulnger24 分钟前
Django 框架(模板)
笔记·python·学习·django
余衫马25 分钟前
Qt for Python:PySide6 入门指南
开发语言·c++·python·qt
python_王子29 分钟前
python_django_跨境电商产品推荐与展示系统[结尾附下载地址]
python·信息可视化·django
好像不对劲34 分钟前
python去除pdf白边
开发语言·python·pdf·kindle
Ethan-D37 分钟前
每日一题#21 二维 DP + 计数类
java·python·算法·leetcode·动态规划
70asunflower40 分钟前
Jupyter Notebook 详细快捷键操作指南
ide·python·jupyter