python之super

子类在继承父类的时候,一般都会在初始化函数中调用父类的__init__函数,举个例子:

python 复制代码
class Parent:
    def __init__(self):
        print("This is Parent class.")

class Child(Parent):
    def __init__(self):
        super().__init__()
        print("This is Child class.")

c = Child()

那为什么会调用呢? 不调是否可以? 再看个例子

python 复制代码
class Parent:
    def __init__(self) -> str:
        self.age = 18
        
    def getAge(self):
        return self.age
    
class Child(Parent):
    def __init__(self) -> str:
        self.name = "Child"
        
        
c = Child()
print(c.getAge())

执行后,会报错,信息如下:

python 复制代码
Traceback (most recent call last):
  File "h:\py_super.py", line 14, in <module>
    print(c.getAge())
          ^^^^^^^^^^
  File "h:\py_super.py", line 6, in getAge
    return self.age
           ^^^^^^^^
AttributeError: 'Child' object has no attribute 'age'

原因:

  1. 子类在继承时,没有触发父类的初始化函数,导致对象属性age缺失。

因此,最好还是调用一下父类的__init__函数。

特别是当有很长的继承关系时,如D继承C,C继承B,B继承A,D类逐个调用多个父类的__init__函数太麻烦,而super()方法可以自动的找到父类的构造方法,并正确的传递参数。

补充知识点:

super函数返回一个代理对象,该对象可以访问父类的方法。

相关推荐
梦想三三12 小时前
Python从零实现AI Agent电商客服(Qwen/Ollama+SQLite源码解析)
人工智能·python·sqlite
鹿鹿学长12 小时前
国赛工业应用数学题:从31省规上工业数据到生产排程,四类高频赛题的破题打法
python·自动化
笨鸟先飞,勤能补拙13 小时前
密码学深度指南 — SecOps 工程师实战手册
人工智能·vscode·python·安全·github·密码学·visual studio
淼澄研学13 小时前
PyTorch核心实操:从张量计算到混合精度训练的5个关键步骤
人工智能·pytorch·python
梦想三三13 小时前
Qwen Function Calling实战:重构电商客服AI Agent
人工智能·python·langchain·大模型·rag
05664613 小时前
agent学习Day23——文件上传与 Embedding 语义检索
python·学习·embedding
leisoo809713 小时前
筹码分布数据分析实战:用Python构建主力建仓成本分析系统
python·数据挖掘·数据分析
淼澄研学13 小时前
PyTorch 2.0 核心机制解析与5个实操方法
人工智能·pytorch·python
rogabet-note13 小时前
cef3和tkinter网页浏览器
python
半兽先生13 小时前
MinerU + LibreOffice 混合架构:搞定 .doc/.ppt 旧格式文档解析与切片
人工智能·python·机器学习·ai·架构