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
相关推荐
ellenwan202618 分钟前
近期AI协作量化实现,先补规则清晰度和流程完整性
人工智能·python
卷无止境24 分钟前
Python 类型注解与运行时反射:从原理到工程实践
后端·python
酷可达拉斯39 分钟前
Linux操作系统-shell编程(0)
linux·运维·服务器·python·云计算
W6580341941 分钟前
2026年AI编程工具实测横评:Claude Code v2.1、Cursor 3.0、Trae SOLO、Copilot、Windsurf 谁更好用?
python·copilot·ai编程
snow@li1 小时前
技术栈对应:Vue (前端) + SpringBoot (Java 后端) =》 Python 全场景配套
python
2501_909509101 小时前
DAY 28
开发语言·python
码云骑士1 小时前
71-Agent记忆系统-短期记忆-长期记忆-向量知识库三层架构
python·架构
卷无止境1 小时前
Python 的 exec 与 eval :动态代码执行的能力、风险与工程实践
后端·python
user-猴子1 小时前
从零构建 2048 游戏,解析“Python-Use”范式的完整闭环
开发语言·python·游戏
郝学胜_神的一滴1 小时前
Python 高级编程 025:二分利器bisect模块:优雅维系有序序列,极致优化检索性能
python·pycharm