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

#问题描述

  • 在学习别人的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"
相关推荐
暮毅18 分钟前
四、Drf认证组件
python·django·drf
DanCheng-studio38 分钟前
毕设 基于大数据情感分析的网络舆情分析系统(源码+论文)
python·毕业设计·毕设
DanCheng-studio40 分钟前
大数据 机器学习毕业设计任务书帮助
python·毕业设计·毕设
985小水博一枚呀1 小时前
【深度学习基础模型】稀疏自编码器 (Sparse Autoencoders, SAE)详细理解并附实现代码。
人工智能·python·深度学习·学习·sae·autoencoder
爱写代码的小朋友1 小时前
Python 中的高阶函数与闭包
开发语言·python
子墨7771 小时前
yield:生成器 ----------------
python
为啥不能修改昵称啊2 小时前
python的extend和append
开发语言·python
Bonne journée2 小时前
python调用父类同名成员
开发语言·python·php
凡人的AI工具箱2 小时前
15分钟学 Python 第38天 :Python 爬虫入门(四)
开发语言·人工智能·后端·爬虫·python
码农超哥同学2 小时前
Python知识点:在Python编程中,如何使用Gensim进行主题建模
开发语言·python·面试·编程