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

#问题描述

  • 在学习别人的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"
相关推荐
用户019027581611 小时前
AlphaFeed 查不到代码返回空?非法/缺后缀 symbol 的行为与处理
python
isfox2 小时前
Python 单元测试:别再用 print 调试了,写个测试一劳永逸
python
用户298698530142 小时前
在 Python 中把 Word 文档转换为 JSON 的三种实现方式
python·json·api
用户0332126663672 小时前
使用 Python 删除 Excel 中的空白行或空白列
python·excel
databook3 小时前
时间序列特征,哪些当时就能算出来
python·数据分析
kevin_org3 小时前
LangChain入门学习(四)
python·学习·langchain·fastapi
特立独行的猫A11 小时前
别再用 nohup 了:让应用在后台常驻的正确姿势与 systemd 服务详解
java·后端·python
吃我一窝jio14 小时前
Python与Go线程模型深度对比
java·开发语言·python
zwd200515 小时前
Manim 怎么放大画面的某一部分?
python·动画·可视化·manim·数学动画
屿华AI15 小时前
AUTOSAR 实战-诊断工具 | UDS 0x27 安全访问的配置化实现:种子密钥算法插件化设计
python·测试工具·汽车