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
相关推荐
纪伊路上盛名在5 小时前
python5.1 数据类dataclass
python·面向对象编程·oop
用户718841750785 小时前
深究 Python 中 int () 函数为何无法转换含小数点的字符串
python
on_pluto_5 小时前
LLaMA: Open and Efficient Foundation Language Models 论文阅读
python·机器学习
小二·5 小时前
mac下解压jar包
ide·python·pycharm
XXX-X-XXJ5 小时前
二:RAG 的 “语义密码”:向量、嵌入模型与 Milvus 向量数据库实操
人工智能·git·后端·python·django·milvus
AI小云6 小时前
【Python与AI基础】Python编程基础:模块和包
人工智能·python
努力努力再努力wz6 小时前
【C++进阶系列】:万字详解智能指针(附模拟实现的源码)
java·linux·c语言·开发语言·数据结构·c++·python
小蕾Java7 小时前
Python详细安装教程(附PyCharm使用)
开发语言·python·pycharm
weixin_307779137 小时前
使用AWS IAM和Python自动化权限策略分析与导出
开发语言·python·自动化·云计算·aws
惜月_treasure7 小时前
从零构建私域知识库问答机器人:Python 全栈实战(附完整源码)
开发语言·python·机器人