python中对super()函数解惑

本文通过三个案例详细阐述了Python中的多重继承和super()函数的使用。在案例一中,展示了当一个类继承多个类,且父类中没有定义的方法时,调用super().run1()会导致AttributeError。案例二解释了super()函数的搜索路径,通过super(Person1,self).run()指定从Person1类开始向上搜索run方法,因此输出结果为'playing'。案例三展示了类的MRO(Method Resolution Order)顺序,通过D类的__mro__属性及super()函数的调用来理解类的继承和方法查找顺序。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

案例一:运行下面的代码结果是什么?

class Person:
    def run(self):
        print('studying')

class Person1:
    def run(self):
        print('working')

class Person2:
    def run(self):
        print('playing')

class Person3(Person,Person1,Person2):

    def run(self):
        super().run1()

p=Person3()
p.run()

执行结果:
AttributeError: ‘super’ object has no attribute ‘run1’

注意:

1、一个类继承多个类时,如果父类中没有提供该方法,类会通过__mro__属性一直向上搜索,如果直到object还没有搜索到该方法,那么将会引发AttributeError异常

案例二:运行下面的代码结果是什么?

class Person:
    def run(self):
        print('studying')

class Person1:
    def run(self):
        print('working')

class Person2:
    def run(self):
        print('playing')

class Person3(Person,Person1,Person2):

    def run(self):
        super(Person1,self).run()

p=Person3()
p.run()

输出结果为:playing;而不是working

注意:

1、super()函数的使用。
使用super()函数时,可以通过super(类名,self)来指定对哪个对象以哪个类为起点向上搜索父类中的方法。
例如:super(Person1,self).run():表示以Person1类为起点,向上搜索self(Person3的对象)的run方法。
Person1向上搜索到了<class ‘main.Person2’>,所以才会输出playing

2、print(Person3.mro)的继承顺序为:(<class ‘main.Person3’>, <class ‘main.Person’>, <class ‘main.Person1’>, <class ‘main.Person2’>, <class ‘object’>)

案例三、更复杂些的继承,和上面的同理

class A:
    def who(self):
        print('A', end='')

class B(A):
    def who(self):
        super(B, self).who()
        print('B', end='')

class C(A):
    def who(self):
        super(C, self).who()
        print('C', end='')

class D(B, C):
    def who(self):
        super(D, self).who()
        print('D', end='')

item = D()
item.who()


print(D.__mro__)

输出结果:
ACBD
(<class ‘main.D’>, <class ‘main.B’>, <class ‘main.C’>, <class ‘main.A’>, <class ‘object’>)

在这里插入图片描述

评论 40
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

敲代码敲到头发茂密

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值