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

#问题描述

  • 在学习别人的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"
相关推荐
开发者小天几秒前
python中的class类
开发语言·python
idwangzhen10 分钟前
GEO优化系统哪家更专业
python·信息可视化
diediedei27 分钟前
机器学习模型部署:将模型转化为Web API
jvm·数据库·python
m0_5613596729 分钟前
使用Python自动收发邮件
jvm·数据库·python
naruto_lnq1 小时前
用Python批量处理Excel和CSV文件
jvm·数据库·python
b2077211 小时前
Flutter for OpenHarmony 身体健康状况记录App实战 - 提醒设置实现
python·flutter·macos·cocoa·harmonyos
2301_822365031 小时前
数据分析与科学计算
jvm·数据库·python
河北小博博1 小时前
分布式系统稳定性基石:熔断与限流的深度解析(附Python实战)
java·开发语言·python
黄连升1 小时前
Python学习第二天,系统学习基础
python·学习
西红市杰出青年1 小时前
CSS 选择器详细教程:原理、语法、方向/“轴”与实战
css·python