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

#问题描述

  • 在学习别人的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"
相关推荐
万笑佛6 小时前
Python 实现Kafka SASL认证生产消费
python
m0_617493948 小时前
Python OpenCV 透视变换(Perspective Transform)详解与实战
开发语言·python·opencv
小李不困还能学8 小时前
PyCharm下载安装与配置教程
ide·python·pycharm
博观而约取厚积而薄发8 小时前
Pytest 从入门到精通,一篇就够(超详细实战教程)
python·测试工具·单元测试·自动化·pytest
imzed8 小时前
使用 Playwright + Pytest 构建 Web UI 自动化测试框架
python·自动化·pytest
普通网友8 小时前
pytest一些常见的插件
开发语言·python·pytest
时空系8 小时前
Python 高性能高压缩打包器 —— 基于 JianPy 语义分析引擎
python
cndes9 小时前
给Miniconda换源,让包下载更迅速
开发语言·python
Metaphor6929 小时前
使用 Python 添加、隐藏和删除 PDF 图层
python·pdf·图层