千家信息网

Python中super()函数如何使用

发表于:2026-11-01 作者:千家信息网编辑
千家信息网最后更新 2026年11月01日,Python中super()函数如何使用,相信很多没有经验的人对此束手无策,为此本文总结了问题出现的原因和解决方法,通过这篇文章希望你能解决这个问题。代码实验展示:# 继承关系 object -> P
千家信息网最后更新 2026年11月01日Python中super()函数如何使用

Python中super()函数如何使用,相信很多没有经验的人对此束手无策,为此本文总结了问题出现的原因和解决方法,通过这篇文章希望你能解决这个问题。

代码实验展示:

# 继承关系 object -> Person -> Student -> SchoolBoy# python2的语法:# class Person(object):# python3的语法:# class Person():class Person():  # class Person(object):  '''定义基类Person'''  def __init__(self, name, age):'''初始化属性name和age'''self.name = name    self.age = age  def printInfo(self):print(  '---我是一个实例对象, 属于类型:{0:^35}   ---我的名字是: {1:{3}<8}   ---我的年龄是: {2:<5}'.format(str(self.__class__), str(self.name), str(self.age), chr(12288)  ))class Student(Person):    '''定义基类Person的子类Student'''  def __init__(self, name, age):'''初始化父类的属性name和age'''super().__init__(name, age)# python2的语法:# super(Student, self).__init__(name, age)# python3的语法:# super().__init__(name, age)  def printInfo(self):print(  '---我是一个实例对象, 属于类型:{0:^35}   ---我的名字是: {1:{3}<8}   ---我的年龄是: {2:<5}'.format(str(self.__class__), str(self.name), str(self.age), chr(12288)  ))class SchoolBoy(Student):    '''定义基类Student的子类SchoolBoy'''  def __init__(self, name, age):'''初始化父类的属性name和age'''super().__init__(name, age)# python2的语法:# super(SchoolBoy, self).__init__(name, age)# python3的语法:# super().__init__(name, age)  def printInfo(self):print(  '---我是一个实例对象, 属于类型:{0:^35}   ---我的名字是: {1:{3}<8}   ---我的年龄是: {2:<5}'.format(str(self.__class__), str(self.name), str(self.age), chr(12288)  ))if __name__ == "__main__":per = Person('林麻子',15)per.printInfo()stu = Student('昊昊',16)stu.printInfo()boy = SchoolBoy('铁凡',17)boy.printInfo()

控制台输出结果:

Windows PowerShell版权所有 (C) Microsoft Corporation。保留所有权利。尝试新的跨平台 PowerShell https://aka.ms/pscore6加载个人及系统配置文件用了 893 毫秒。(base) PS C:\Users\chenxuqi\Desktop\News4cxq\test4cxq> conda activate ssd(ssd) PS C:\Users\chenxuqi\Desktop\News4cxq\test4cxq>  & 'D:\Anaconda3\envs\ssd\python.exe' 'c:\Users\chenxuqi\.vscode\extensions\ms-python.python-2020.12.424452561\pythonFiles\lib\python\debugpy\launcher' '56869' '--' 'c:\Users\chenxuqi\Desktop\News4cxq\test4cxq\test17.py'---我是一个实例对象, 属于类型:             ---我的名字是: 林麻子        ---我的年龄是: 15   ---我是一个实例对象, 属于类型:            ---我的名字是: 昊昊         ---我的年龄是: 16   ---我是一个实例对象, 属于类型:          ---我的名字是: 铁凡         ---我的年龄是: 17   (ssd) PS C:\Users\chenxuqi\Desktop\News4cxq\test4cxq>

看完上述内容,你们掌握Python中super()函数如何使用的方法了吗?如果还想学到更多技能或想了解更多相关内容,欢迎关注行业资讯频道,感谢各位的阅读!

0