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

相关推荐
henrylin99999 小时前
Hermes Agent 核心运行系统调用流程--源码分析
开发语言·人工智能·python·机器学习·hermesagent
wgzrmlrm749 小时前
如何加固SQL环境部署_删除默认安装的示例数据库
jvm·数据库·python
珎珎啊9 小时前
Python3 字符串核心知识点
开发语言·python
lbb 小魔仙9 小时前
Python_多模态大模型实战指南
开发语言·python
XDHCOM10 小时前
Python os.system() 和 subprocess 怎么选?运行系统命令哪个更好用?
开发语言·网络·python
雨墨✘10 小时前
golang如何实现设备指纹识别_golang设备指纹识别实现详解
jvm·数据库·python
yfndsb10 小时前
从入门到落地:OpenClaw 全面介绍与全平台本地部署保姆级教程
人工智能·python·ai
qq_2837200510 小时前
Python Web 开发:Flask 快速入门教程
python·flask·web
加勒比海带6610 小时前
目标检测算法——低空智能实验室开放数据集汇总附下载链接【点赞+收藏】
大数据·图像处理·人工智能·python·深度学习·目标检测·计算机视觉
PILIPALAPENG11 小时前
第2周 Day 4:英语 Agent Web 版上线:从命令行到浏览器
前端·人工智能·python