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

#问题描述

  • 在学习别人的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"
相关推荐
我什么都学不会31 分钟前
Python练习作业3
开发语言·python
板面华仔39 分钟前
机器学习入门(二)——逻辑回归 (Logistic Regression)
python·机器学习
Hgfdsaqwr41 分钟前
使用Flask快速搭建轻量级Web应用
jvm·数据库·python
GHZhao_GIS_RS1 小时前
python中的sort和sorted用法汇总
python·排序·列表
永恒的溪流1 小时前
环境出问题,再修改
pytorch·python·深度学习
ruxshui1 小时前
Python多线程环境下连接对象的线程安全管理规范
开发语言·数据库·python·sql
大模型玩家七七1 小时前
向量数据库实战:从“看起来能用”到“真的能用”,中间隔着一堆坑
数据库·人工智能·python·深度学习·ai·oracle
2301_763472461 小时前
使用PyQt5创建现代化的桌面应用程序
jvm·数据库·python
爱学习的阿磊1 小时前
Web开发与API
jvm·数据库·python
qq_192779871 小时前
Python多线程与多进程:如何选择?(GIL全局解释器锁详解)
jvm·数据库·python