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

#问题描述

  • 在学习别人的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"
相关推荐
杰瑞哥哥3 分钟前
快速搭建Web前端(streamlit使用指南)
python·信息可视化·web·模型部署
小途软件5 分钟前
基于计算机视觉的课堂行为编码研究
人工智能·python·深度学习·计算机视觉·语言模型·自然语言处理·django
智航GIS5 分钟前
9.2 多进程入门
数据库·python
小途软件6 分钟前
基于计算机视觉的桥梁索力测试方法
人工智能·python·语言模型·自然语言处理·django
yousuotu13 分钟前
基于Python实现水果新鲜度分类
开发语言·python·分类
Data_agent14 分钟前
微店商品列表API接口指南
大数据·数据库·python
吴老弟i16 分钟前
基于 VSCode 实现 Python 开发与调试 | 环境配置搭建 | PIP Anaconda
vscode·python·pip
七夜zippoe18 分钟前
异步编程实战:构建高性能Python网络应用
开发语言·python·websocket·asyncio·aiohttp
tianyuanwo19 分钟前
Python虚拟环境深度解析:从virtualenv到virtualenvwrapper
开发语言·python·virtualenv
越甲八千20 分钟前
ORM 的优势
数据库·python