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
相关推荐
ZTLJQ2 小时前
序列化的艺术:Python JSON处理完全解析
开发语言·python·json
H5css�海秀3 小时前
今天是自学大模型的第一天(sanjose)
后端·python·node.js·php
阿贵---3 小时前
使用XGBoost赢得Kaggle比赛
jvm·数据库·python
无敌昊哥战神3 小时前
【LeetCode 257】二叉树的所有路径(回溯法/深度优先遍历)- Python/C/C++详细题解
c语言·c++·python·leetcode·深度优先
李昊哲小课5 小时前
第1章-PySide6 基础认知与环境配置
python·pyqt·pyside
2401_894241925 小时前
用Pygame开发你的第一个小游戏
jvm·数据库·python
Zzzz_my6 小时前
正则表达式(RE)
pytorch·python·正则表达式
天天鸭7 小时前
前端仔写了个 AI Agent,才发现大模型只干了 10% 的活
前端·python·ai编程
setmoon2147 小时前
使用Scikit-learn构建你的第一个机器学习模型
jvm·数据库·python
2401_833197738 小时前
为你的Python脚本添加图形界面(GUI)
jvm·数据库·python