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

#问题描述

  • 在学习别人的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"
相关推荐
RS&5 小时前
DAHITI水位数据产品批量下载(python)
python
27669582925 小时前
逆向视角解决:wsgsig dd03/dd05算法生成
python·滴滴出行·dd03·dd05·wsgsig·wsgsig算法·wsgsig逆向
AC赳赳老秦5 小时前
技术文章素材收集自动化:用 OpenClaw 自动爬取行业资讯、技术热点、优质文章
运维·开发语言·python·自动化·wpf·deepseek·openclaw
SilentSamsara5 小时前
模型评估与超参调优:交叉验证、Optuna 与模型选择策略
人工智能·python·深度学习·机器学习·青少年编程
叫我:松哥5 小时前
基于LSTM与ARIMA的城市空气质量分析与预测系统
人工智能·python·rnn·算法·机器学习·flask·lstm
指尖在键盘上舞动5 小时前
RKNN 模型部署:onnx转rknn后精度下降 —— 精度调优与问题排查
python·ubuntu·rk3588·rknn·onnx·npu
CodeSheep程序羊5 小时前
宇树科技,即将上市!
java·c语言·c++·人工智能·python·科技·硬件工程
AI玫瑰助手5 小时前
Python函数:内置函数(len/max/min/sorted等)详解
android·开发语言·python
ziyitty5 小时前
解决Windows下Bash调用Python输出中文乱码的问题
windows·python·bash
栈溢出了5 小时前
torch.gather 用法笔记
pytorch·python·深度学习