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
相关推荐
gnawkhhkwang43 分钟前
Flask + YARA-Python*实现文件扫描功能
后端·python·flask
yj15581 小时前
二手房翻新时怎样装修省钱?
python
max5006001 小时前
复现论文《A Fiber Bragg Grating Sensor System for Train Axle Counting》
开发语言·python·深度学习·机器学习·matlab·transformer·机器翻译
WSSWWWSSW1 小时前
Python高级编程与实践:Python网络编程基础与实践
开发语言·网络·python
mortimer2 小时前
Python GUI 应用启动优化实战:从3分钟到“秒开”的深度历程
python·github·pyqt
竹子_232 小时前
贪心算法解析
python·算法·贪心算法
三道杠卷胡2 小时前
【AI News | 20250804】每日AI进展
人工智能·python·语言模型·github·aigc
小沈熬夜秃头中୧⍤⃝2 小时前
Python 基础语法(二):流程控制语句详解
开发语言·数据库·python
max5006002 小时前
基于开源人脸识别模型实现情绪识别功能
python·深度学习·开源·transformer
黄晓魚3 小时前
open3d python 鞋底点云点胶路径识别
开发语言·python·open3d