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

#问题描述

  • 在学习别人的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"
相关推荐
禹凕12 分钟前
滑动窗口算法实战指南
python·算法
论文复现现场1 小时前
RTX 4090 24GB 能跑 Qwen3.8-27B 吗?单卡显存计算与云端部署指南
人工智能·python·云计算·llama·gpu算力
Patrick在香港1 小时前
模型路由器实测:12 个任务省 77%,旗舰过载时的降级要打出显式标记
python·llm·智能路由器·api·架构设计·成本优化
Looooking1 小时前
Python 之 jwt 令牌生成和校验
python·jwt
2601_962295992 小时前
嵌入式开发语言用哪个最好,C,python或者其他
c语言·python·嵌入式开发·开发效率·系统资源
菜鸡66662 小时前
绕过cf验证,部署 FlareSolverr 服务使用request处理
python·cloudflare
前端 贾公子3 小时前
第10章:RAG(2)
开发语言·python
2601_962299494 小时前
使用 Python 将 CSV 转为 PDF(含表格样式美化)
python·pdf·csv·spire.xls·表格样式
2601_962077984 小时前
利用Python,四步掌握机器学习
python·机器学习·数据挖掘·数据分析·编程
axinawang4 小时前
requests--爬取网页内容
python