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

#问题描述

  • 在学习别人的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"
相关推荐
yangmf20401 小时前
APM(三):监控 Python 服务链
大数据·运维·开发语言·python·elk·elasticsearch·搜索引擎
yangmf20401 小时前
APM(二):监控 Python 服务
大数据·python·elasticsearch·搜索引擎
CoderJia程序员甲1 小时前
GitHub 热榜项目 - 日榜(2025-11-23)
python·开源·github·mcp
AI爱好者2 小时前
WordPress保卫战:用Python分析日志并封禁恶意爬虫
python
nvd112 小时前
Gidgethub 使用指南
开发语言·python
___波子 Pro Max.2 小时前
Python模块导入详解与最佳实践
python
CNRio4 小时前
ZUC国密算法深度研究:原理、实现与应用(Python、Rust)
python·算法·rust
Python大数据分析@4 小时前
数据分析为什么常用Jupyter而不是直接使用Python脚本或Excel?
python·jupyter·数据分析
一株菌子4 小时前
10.9总结
开发语言·python
o***Z4485 小时前
Python包管理工具
开发语言·python