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

#问题描述

  • 在学习别人的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"
相关推荐
FreakStudio1 小时前
不用装软件!这款MicroPython浏览器 IDE :让你在手机上也能调试树莓派 Pico
python·单片机·嵌入式·电子diy·tinyml
m0_743470372 小时前
使用Python进行PDF文件的处理与操作
jvm·数据库·python
数据科学小丫4 小时前
Python 数据存储操作_数据存储、补充知识点:Python 与 MySQL交互
数据库·python·mysql
Knight_AL4 小时前
Nacos 启动问题 Failed to create database ’D:\nacos\nacos\data\derby-data’
开发语言·数据库·python
查古穆5 小时前
python进阶-Pydantic模型
开发语言·python
佳木逢钺6 小时前
PyQt界面美化系统高级工具库:打造现代化桌面应用的完整指南
python·pyqt
工頁光軍6 小时前
基于Python的Milvus完整使用案例
开发语言·python·milvus
Csvn6 小时前
特殊方法与运算符重载
python
xht08326 小时前
PHP vs Python:编程语言终极对决
开发语言·python·php
2401_879693877 小时前
使用Python控制Arduino或树莓派
jvm·数据库·python