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

#问题描述

  • 在学习别人的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"
相关推荐
大闲在人4 分钟前
Trae builder 实战: 让 C++ 函数像 Python 一样返回多个值
c++·python·ai编程
柠檬丶抒情12 分钟前
Rust深度学习框架Burn 0.20是否能超过python?
python·深度学习·rust·vllm
reesn15 分钟前
celery 使用说明
python
ValhallaCoder23 分钟前
Day50-图论
数据结构·python·算法·图论
好好学操作系统25 分钟前
notion+excel自动创建表格| 了解了notion api
数据库·python·oracle·excel·notion
一晌小贪欢27 分钟前
用 PyQt5 做一个「批量目录重命名」工具,并打包成带图标的 EXE
开发语言·驱动开发·python·python基础·python小白
sunfove31 分钟前
Python制作小游戏:用线性代数思想构建 2048 游戏引擎
python·线性代数·游戏引擎
小二·32 分钟前
Python Web 开发进阶实战:时空数据引擎 —— 在 Flask + Vue 中构建实时地理围栏与轨迹分析系统
前端·python·flask
Uncertainty!!33 分钟前
pycharm本地Failed to open X display(exiting)
ide·python·pycharm
小二·34 分钟前
Python Web 开发进阶实战:可验证网络 —— 在 Flask + Vue 中实现去中心化身份(DID)与零知识证明(ZKP)认证
前端·网络·python