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

#问题描述

  • 在学习别人的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"
相关推荐
KIHU快狐1 小时前
KIHU快狐|vr全景体验一体机高配置硬件带来更流畅操作体验
python
阿轲Jackson1 小时前
AttributeError: ‘WebDriver‘ object has no attribute ‘find_element_by_id‘
python·selenium
喵手1 小时前
Python爬虫实战:Apple Music华语榜每日增量追踪与峰值计算!
爬虫·python·爬虫实战·零基础python爬虫教学·apply music·华语榜单·每日增量与峰值计算
烟锁池塘柳01 小时前
【已解决】解决 ModuleNotFoundError: No module named ‘exceptions‘
python·pip
Lw中1 小时前
RAG切片语义割裂怎么办?
python·rag文本分割·大模型应用基础
aiguangyuan1 小时前
多模态AI实战:CLIP模型原理与代码深度剖析
人工智能·python·机器学习·nlp
xin^_^2 小时前
java基础学习
java·开发语言·python
坐吃山猪2 小时前
Tree-sitter语法树解析
开发语言·python·tree-sitter
郝学胜-神的一滴2 小时前
深度解析:深度学习核心特性与行业实践
人工智能·python·rnn·深度学习·神经网络·cnn
清水白石0082 小时前
《解锁 Python 潜能:从内存模型看可变与不可变对象,及其实战最佳实践》
大数据·开发语言·python