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
相关推荐
奔跑吧邓邓子35 分钟前
【Python爬虫(12)】正则表达式:Python爬虫的进阶利刃
爬虫·python·正则表达式·进阶·高级
码界筑梦坊1 小时前
基于Flask的京东商品信息可视化分析系统的设计与实现
大数据·python·信息可视化·flask·毕业设计
pianmian11 小时前
python绘图之箱型图
python·信息可视化·数据分析
csbDD2 小时前
2025年网络安全(黑客技术)三个月自学手册
linux·网络·python·安全·web安全
赔罪3 小时前
Python 高级特性-切片
开发语言·python
伊一大数据&人工智能学习日志3 小时前
selenium爬取苏宁易购平台某产品的评论
爬虫·python·selenium·测试工具·网络爬虫
说是用户昵称已存在4 小时前
Pycharm+CodeGPT+Ollama+Deepseek
ide·python·ai·pycharm
Fansv5874 小时前
深度学习-2.机械学习基础
人工智能·经验分享·python·深度学习·算法·机器学习
wang_yb4 小时前
『Python底层原理』--Python对象系统探秘
python·databook
databook4 小时前
『Python底层原理』--Python对象系统探秘
后端·python