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

#问题描述

  • 在学习别人的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"
相关推荐
天天进步20154 分钟前
如何通过 Py_Initialize 实现 C++ 对 Python 的嵌入调用
python
Niuguangshuo7 分钟前
# PyTorch 中 `nn.ModuleList` 详解
人工智能·pytorch·python
BoBoZz1918 分钟前
ResetCameraOrientation 保存、修改和恢复摄像机的精确视角参数
python·vtk·图形渲染·图形处理
aloha_78928 分钟前
python基础面经八股
开发语言·python
西西弗Sisyphus44 分钟前
极限的常数倍数性质证明和可视化代码
python·微积分·极限
小鸡吃米…1 小时前
机器学习——生命周期
人工智能·python·机器学习
bugtraq20211 小时前
PentestGPT的部署和使用本地大模型的调试记录
linux·服务器·python
databook1 小时前
回归分析全家桶(16种回归模型实现方式总结)
人工智能·python·机器学习
猴子年华、1 小时前
【每日一技】:GitHub 精确查询
开发语言·python·github