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

相关推荐
java1234_小锋1 分钟前
Scikit-learn Python机器学习 - 分类算法 - 线性模型 逻辑回归
python·机器学习·scikit-learn
倔强的石头_20 分钟前
你的 Python 为什么“优雅地慢”?——读《极速Python:高性能编码、计算与数据分析》
python
程序猿 小项目大搞头27 分钟前
视频加水印,推荐使用运营大管家-视频批量加水印软件
python
Adorable老犀牛1 小时前
可遇不可求的自动化运维工具 | 2 | 实施阶段一:基础准备
运维·git·vscode·python·node.js·自动化
xchenhao2 小时前
SciKit-Learn 全面分析 digits 手写数据集
python·机器学习·分类·数据集·scikit-learn·svm·手写
胡耀超2 小时前
7、Matplotlib、Seaborn、Plotly数据可视化与探索性分析(探索性数据分析(EDA)方法论)
python·信息可视化·plotly·数据挖掘·数据分析·matplotlib·seaborn
tangweiguo030519872 小时前
Django REST Framework 构建安卓应用后端API:从开发到部署的完整实战指南
服务器·后端·python·django
Dfreedom.2 小时前
在Windows上搭建GPU版本PyTorch运行环境的详细步骤
c++·人工智能·pytorch·python·深度学习
兴科Sinco2 小时前
[leetcode 1]给定一个整数数组 nums 和一个整数目标值 target,请你在该数组中找出和为目标值 target 的那两个整数[力扣]
python·算法·leetcode
程序员奈斯2 小时前
Python深度学习:NumPy数组库
python·深度学习·numpy