python的类中的super是做什么的

其实就是子类调用一下父类的构造函数(或者其他函数也行)。:

在 Python 中,super() 是一个用于调用父类(或基类)的方法。它通常在子类中使用,以便调用其父类的初始化方法或其他方法,从而确保父类的初始化代码在子类中也得到了执行。

python 复制代码
class Parent:
    def __init__(self, name):
        self.name = name
        print(f'Parent initialized with name: {self.name}')
    
    def greet(self):
        print(f'Hello, my name is {self.name}')

class Child(Parent):
    def __init__(self, name, age):
        super().__init__(name)  # 调用父类的 __init__ 方法
        self.age = age
        print(f'Child initialized with name: {self.name} and age: {self.age}')
    
    def greet(self):
        super().greet()  # 调用父类的 greet 方法
        print(f'I am {self.age} years old')

# 使用示例
child = Child('Alice', 10)
child.greet()

输出:

python 复制代码
Parent initialized with name: Alice
Child initialized with name: Alice and age: 10
Hello, my name is Alice
I am 10 years old
相关推荐
这里有鱼汤17 小时前
小白必看:QMT里的miniQMT入门教程
后端·python
TF男孩1 天前
ARQ:一款低成本的消息队列,实现每秒万级吞吐
后端·python·消息队列
该用户已不存在1 天前
Mojo vs Python vs Rust: 2025年搞AI,该学哪个?
后端·python·rust
站大爷IP1 天前
Java调用Python的5种实用方案:从简单到进阶的全场景解析
python
用户8356290780512 天前
从手动编辑到代码生成:Python 助你高效创建 Word 文档
后端·python
c8i2 天前
python中类的基本结构、特殊属性于MRO理解
python
liwulin05062 天前
【ESP32-CAM】HELLO WORLD
python
Doris_20232 天前
Python条件判断语句 if、elif 、else
前端·后端·python
Doris_20232 天前
Python 模式匹配match case
前端·后端·python
这里有鱼汤2 天前
Python量化实盘踩坑指南:分钟K线没处理好,小心直接亏钱!
后端·python·程序员