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

相关推荐
梦想不只是梦与想21 分钟前
Python 中的装饰器
python·装饰器
我叫唧唧波1 小时前
Python+AI 全栈学习笔记
人工智能·python·学习
copyer_xyf1 小时前
Python 异常处理
前端·后端·python
麻雀飞吧2 小时前
期货多合约策略目标持仓怎么更新才不乱
python·区块链
Cthy_hy2 小时前
拓扑排序超详解:原理 + Kahn 贪心算法
python·算法·贪心算法
LSssT.2 小时前
【01】Python 机器学习
开发语言·python
为爱停留2 小时前
给智能体装上「刹车」:中断(Interrupts)与人工审批全解析
python
l1t3 小时前
DeepSeek总结的使用实体-组件-系统和基于存在性处理进行Python编程39-40
开发语言·python
曾阿伦3 小时前
Python 搭建简易HTTP服务
开发语言·python·http
MIUMIUKK3 小时前
从语法层面,看懂 Python 的特殊处
java·开发语言·python