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

相关推荐
智航GIS31 分钟前
10.7 pyspider 库入门
开发语言·前端·python
副露のmagic42 分钟前
更弱智的算法学习 day25
python·学习·算法
hudawei9961 小时前
Flask 与 FastAPI 对比分析
python·flask·fastapi
寻星探路1 小时前
【Python 全栈测开之路】Python 基础语法精讲(一):常量、变量与运算符
java·开发语言·c++·python·http·ai·c#
智航GIS2 小时前
10.5 PyQuery:jQuery 风格的 Python HTML 解析库
python·html·jquery
小兔崽子去哪了2 小时前
机器学习,梯度下降,拟合,正则化,混淆矩阵
python·机器学习
缘友一世2 小时前
PyCharm连接autodl平台服务(python解释器&jupyter lab)
python·jupyter·pycharm
a程序小傲2 小时前
得物Java面试被问:方法句柄(MethodHandle)与反射的性能对比和底层区别
java·开发语言·spring boot·后端·python·面试·职场和发展
华研前沿标杆游学2 小时前
2026走进滕讯:小游戏×大模型产业交流记
python
_codemonster3 小时前
计算机视觉入门到实战系列(八)Harris角点检测算法
python·算法·计算机视觉