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

#问题描述

  • 在学习别人的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"
相关推荐
清水白石0088 小时前
Python 纯函数编程:从理念到实战的完整指南
开发语言·python
twilight_4698 小时前
机器学习与模式识别——机器学习中的搜索算法
人工智能·python·机器学习
Jia ming9 小时前
《智能法官软件项目》—罪名初判模块
python·教学·案例·智能法官
Jia ming9 小时前
《智能法官软件项目》—法律文书生成模块
python·教学·案例·智能法官软件
曦月逸霜9 小时前
Python数据分析——个人笔记(持续更新中~)
python
海棠AI实验室9 小时前
第六章 从“能用”到“能交付”的关键一刀:偏好对齐(Preference Alignment)数据工程
python·私有模型训练
百锦再10 小时前
Java多线程编程全面解析:从原理到实战
java·开发语言·python·spring·kafka·tomcat·maven
Jia ming10 小时前
《智能法官软件项目》—法律计算器模块
python·教学·案例·智能法官
爱华晨宇10 小时前
Python列表入门:常用操作与避坑指南
开发语言·windows·python
一切顺势而行10 小时前
python 面向对象
开发语言·python