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

#问题描述

  • 在学习别人的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"
相关推荐
中微极客1 小时前
TensorFlow模型量化实战:从精度到延迟的优化指南
人工智能·python·tensorflow
仙人球部落2 小时前
-python-LangGraph框架(3-31-LangGraph 「合并式状态管理」的原理与实践)
开发语言·javascript·python
蜡笔削薪3 小时前
财联支付异地拓展商户的区域限制是否符合监管规定?
大数据·python
印度神油93 小时前
Windows Python 打包实战:Nuitka 环境踩坑总结与 CI 自动化构建全指南
windows·python·ci/cd
chouchuang3 小时前
day-025-面向对象-上
开发语言·python
Csvn5 小时前
Python 开发技巧:标准库深度挖掘
后端·python
li星野5 小时前
二分查找的三重变奏:有序区间、旋转最小值与平方根——从“猜数字”到“向量检索”的思维演化
python
RSTJ_16256 小时前
PYTHON+AI LLM DAY ONE HUNDRED AND THREE
开发语言·人工智能·python
简~7686 小时前
python openpyxl处理Excel成绩表自动统计
python·大学生
梦想不只是梦与想6 小时前
Python 官方包管理器pip
python·pip