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

#问题描述

  • 在学习别人的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"
相关推荐
我的xiaodoujiao5 分钟前
使用 Python 语言 从 0 到 1 搭建完整 Web UI自动化测试学习系列 28--开源电商商城系统项目实战--封装注册页面
python·学习·测试工具·pytest
天天找自己9 分钟前
TransNeXt 深度解析:聚合注意力机制的突破性视觉骨干网络
人工智能·pytorch·python·深度学习·神经网络
AI小云14 分钟前
【数据操作与可视化】Matplotlib绘图-基础功能
python·数据可视化
m***667322 分钟前
Python 爬虫实战案例 - 获取社交平台事件热度并进行影响分析
开发语言·爬虫·python
I_ltt_Itw,30 分钟前
Python多线程
服务器·python·pycharm
Hello.Reader32 分钟前
Flink SQL 数据类型从 INT 到 VARIANT 的完整实战指南
python·sql·flink
vi121231 小时前
ENVI 地形量化与植被指数反演
开发语言·python
rising start1 小时前
一、FastAPI入门
python·fastapi·端口
闲人编程1 小时前
Flask应用工厂模式:构建可扩展的大型应用
后端·python·flask·工厂模式·codecapsule·应用工厂
LitchiCheng1 小时前
Mujoco 检验 KDL 和 Pinocchio 运动学 FK 是否一致
人工智能·python