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

#问题描述

  • 在学习别人的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"
相关推荐
紫金修道1 天前
【DeepAgent】概述
开发语言·数据库·python
书到用时方恨少!1 天前
Python multiprocessing 使用指南:突破 GIL 束缚的并行计算利器
开发语言·python·并行·多进程
Warson_L1 天前
Python 常用内置标准库
python
Warson_L1 天前
Python 函数的艺术 (Functions)
python
Warson_L1 天前
Python 流程控制与逻辑
后端·python
long_songs1 天前
手柄键盘映射器【github链接见文末 】
python·游戏·计算机外设·pygame·软件推荐·手柄映射键盘
必然秃头1 天前
Python 环境安装及项目构建指南
python
Warson_L1 天前
Python 四大组合数据类型 (Collection Types)
后端·python
廋到被风吹走1 天前
【AI】Codex 多语言实测:Python/Java/JS/SQL 效果横评
java·人工智能·python
Warson_L1 天前
Python 数据类型核心笔记
python