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函数返回一个代理对象,该对象可以访问父类的方法。

相关推荐
夏天拐跑了西瓜5 小时前
一文入门LangChain:从框架认知到构建你的第一个AI Agent
python·langchain·conda·agent
魔猴疯猿6 小时前
从0到1用Python开发第一个智能体
人工智能·python·深度学习·神经网络·机器学习
xiaoqi01957 小时前
机器学习因子分析实战:从量化特征到可视化决策
人工智能·python·机器学习
Escalating_xu8 小时前
【Python】基础语法(1):常量、变量、类型、输入输出与运算符
开发语言·python
happylifetree8 小时前
Python14:核心语法-数据存储与运算-字符串定义
python
hhb_6188 小时前
AIRAGDebug:一键定位RAG链路异常
人工智能·python·算法
小静AI工程实验室8 小时前
asyncio.Queue 有界队列实战:背压、task_done、join 与异常收尾
python
小凡geo8 小时前
本地商家 GEO:用脚本一键生成 FAQPage 结构化数据,让 AI 切片更稳
开发语言·人工智能·python·microsoft·搜索引擎·ai
Zhou1411368 小时前
SpringBoot_03_Web开发
前端·spring boot·python
weixin199701080169 小时前
《1688物流API接口边界:logistics.trace.get 与 freight.template.list 的隐藏约束》(附Python源码)
windows·python·list