怎么理解Python类中的super函数

本文介绍了Python中super函数的主要作用,它常用于子类构造函数中,调用父类的构造函数,避免重复代码。通过实例展示了super函数的使用方法,包括单继承和多重继承的情况,并对比了super与直接调用父类方法的区别。此外,还探讨了super在多继承场景下的行为,以及其与直接父类引用的不同。
摘要由CSDN通过智能技术生成

前言

在Python类的继承中,经常能看到super函数的存在,那super函数主要的作用,以及如何理解和使用好这个函数?本次教程将详细讲解,希望大家看到最后,并按照代码实际操作下。

常见用途

我们举一个简单例子,我们父类是Human,有两个属性,分别是姓名和性别;然后定义一个子类Student。

class Human:

    def __init__(self, name, sex):
        self.name = name
        self.sex = sex
        print('parent')


class Student(Human):

    pass


stu_1 = Student('lisi', 'male')
print(stu_1.name)

parent
lisi

这里Student没有构造函数,所以会去父类中寻找构造函数。这时候我们需要在子类中加入构造函数,并需要name,sex,score三个属性,那我们如果直接写就应该是下面这种代码。

class Human:

    def __init__(self, name, sex):
        self.name = name
        self.sex = sex
        print('parent')


class Student(Human):

    def __init__(self, name, sex, score):
        self.name = name
        self.sex = sex
        self.score = score
        print('child')

stu_1 = Student('lisi', 'male', 97)
print(stu_1.score)

child
97

你会发现父类和子类都有相同的两行代码。

self.name = name
self.sex = sex

这显然和我们优雅的Python格格不入,所以super函数来了,我们直接看代码。

class Human:

    def __init__(self, name, sex):
        self.name = name
        self.sex = sex
        print('parent')


class Student(Human):

    def __init__(self, name, sex, score):
        super().__init__(name, sex)
        self.score = score
        print('child')

stu_1 = Student('lisi', 'male', 97)
print(stu_1.score)

parent
child
97

通过代码我们可以看出,super函数常常用于子类的构造函数中,用于调用父类(超类)的构造函数,并且不会显式引用基类。

之所以说不用显式引用基类,是因为通过调用父类方法也能实现功能。

class Human:

    def __init__(self, name, sex):
        self.name = name
        self.sex = sex
        print('parent')


class Student(Human):

    def __init__(self, name, sex, score):
        Human.__init__(self, name, sex)
        self.score = score
        print('child')

stu_1 = Student('lisi', 'male', 97)
print(stu_1.score)

parent
child
97

理解super函数

我将通过下面几个进阶的知识点让你理解super函数。

首先我们还是来总结下super函数的语法。

super(type[, object-or-type])

super(Student, self).__init__()  #python2写法
super().__init__()  #python3写法
不仅仅是用于构造函数

super函数虽常用于构造函数,但是父类的其他函数一样也是可以用super函数的。

class A:
    def add(self, x):
        y = x + 1
        print(y)


class B(A):
    def add(self, x):
        super().add(x)


b = B()
b.add(2)

# 3

之所以不常用,我认为是既然继承了父类,那子类就可以直接调用父类的方法,这样做只是多此一举。

class A:
    def add(self, x):
        y = x + 1
        print(y)


class B(A):
    pass


b = B()
b.add(2)

# 3
多重继承可能就不一样了

根据上面的案例,我们可以看出super函数是直接调用基类的构造函数,但是多重继承不一样,他是调用继承顺序的下一个类,而不是父类。

class Base:
    def __init__(self):
        print("enter Base")
        print("leave Base")

class A(Base):
    def __init__(self):
        print("enter A")
        super().__init__()
        print("leave A")

class B(Base):
    def __init__(self):
        print("enter B")
        super().__init__()
        print("leave B")

class C(A, B):
    def __init__(self):
        print("enter C")
        super().__init__()
        print("leave C")

C()

enter C
enter A
enter B
enter Base
leave Base
leave B
leave A
leave C

继承关系为C—A—B—Base,所以程序会先去A,再到B,最后到Base。

super函数和直接调用父类方法的区别

在单继承时,我们看到super和直接调用父类方法得到的结果是一样的,只是不会显式引用基类。但多重继承就不要了,我把上面的代码进行了修改,我相信你能看懂区别。

class Base:
    def __init__(self):
        print("enter Base")
        print("leave Base")

class A(Base):
    def __init__(self):
        print("enter A")
        Base.__init__(self)
        print("leave A")

class B(Base):
    def __init__(self):
        print("enter B")
        Base.__init__(self)
        print("leave B")

class C(A, B):
    def __init__(self):
        print("enter C")
        A.__init__(self)
        B.__init__(self)
        print("leave C")

C()

enter C
enter A
enter Base
leave Base
leave A
enter B
enter Base
leave Base
leave B
leave C

最后,由于本人时间和能力有限,如有错误,请批评指正,我们下期再见~

Python中,super()函数用于调用父类的方法。它的作用是在子类中调用父类的方法,以便实现方法的重写和扩展。super()函数可以在子类的方法中调用父类的同名方法,而不需要直接指定父类的名称。 super()函数的语法格式为super().method_name(),其中method_name是要调用的父类方法的名称。super()函数既可以在普通方法中使用,也可以在类方法中使用。在普通方法中使用super()函数时,它会自动将当前实例作为第一个参数传递给父类方法。在类方法中使用super()函数时,它会将当前类作为第一个参数传递给父类方法。 举个例子,假设有一个父类A和一个子类B,子类B继承自父类A。如果在子类B中重写了父类A的方法add(),可以使用super().add()调用父类A中的add()方法,实现对父类方法的扩展。 总结一下,Python中的super()函数的作用就是在子类中调用父类的方法,以实现方法的重写和扩展。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* [Python中的super函数,你熟吗?](https://blog.csdn.net/luccs624061082/article/details/126872837)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] - *3* [Pythonsuper()函数](https://blog.csdn.net/weixin_46713695/article/details/125114605)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值