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

#问题描述

  • 在学习别人的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"
相关推荐
徐先生 @_@|||6 小时前
基于Translation插件实现在pycharm本地翻译并阅读英文资料
ide·python·pycharm
xcbrand6 小时前
文旅行业品牌策划公司找哪家
大数据·运维·人工智能·python
好家伙VCC7 小时前
**发散创新:基于Rust的轻量级权限管理库设计与开源许可证实践**在现代分布式系统中,**权限控制(RBAC
java·开发语言·python·rust·开源
Dxy12393102167 小时前
Python序列标注模型上下文纠错详解
开发语言·python
ZhengEnCi7 小时前
P2H-Python字符串格式化完全指南-format和f-string的Python编程利器
python
HaiXCoder7 小时前
python从入门到精通-第5章: 函数式编程 — Python的函数式风格
python
HaiXCoder7 小时前
python从入门到精通-第0章: 思维模式碰撞
python
HaiXCoder7 小时前
python从入门到精通-第3章: 数据结构 — Python的"瑞士军刀
python
Orange_sparkle7 小时前
learn claude code学习记录-S02
java·python·学习
小郑加油7 小时前
python学习Day1:python的安装与环境搭载
python·学习·小白记录,保姆式教程