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

#问题描述

  • 在学习别人的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"
相关推荐
Codefengfeng39 分钟前
Python Base环境中加包的方法
开发语言·python
清水白石00840 分钟前
《Python 编程全景解析:从核心精要到测试替身(Test Doubles)五大武器的实战淬炼》
开发语言·python
如若1232 小时前
AutoDL云服务器 NVIDIA 570驱动 EGL渲染修复全记录
运维·服务器·python
甲枫叶2 小时前
【claude】Claude Code正式引入Git Worktree原生支持:Agent全面实现并行独立工作
java·人工智能·git·python·ai编程
清水白石0082 小时前
《Python 编程全景解析:从核心精要到 Hypothesis 属性基测试的边界探索》
开发语言·python
勇往直前plus3 小时前
深入理解 Python 内存模型:模块、类、对象的存储与运行机制
开发语言·python
yunhuibin3 小时前
NIN网络学习
人工智能·python·深度学习·神经网络·学习
派大星-?4 小时前
自动化测试五模块一框架(下)
开发语言·python
两万五千个小时4 小时前
构建mini Claude Code:02 - 把 Bash 拆成专用工具(read_file, write_file 等)
人工智能·python
henry1010105 小时前
Ansible自动化运维全攻略(AI生成)
linux·运维·python·ansible·devops