面向对象编程——super进阶(十)

一、入门使用

在python中,使用super最常见的让子类继承父类。在这种情况下,当前类和对象可以作为super函数的参数使用,调用函数返回的任何方法都是调用超类的方法,而不是当前类的方法。

class Information(object):
    def __init__(self,name,age):
        self.name = name
        self.age = age

class Job_Information(Information):
    def __init__(self,name,age,job_time):
        # Information.__init__(self,name,age)
        super(Job_Information,self).__init__(name,age)
        self.job_time = job_time

在类的继承中,如果重新定义某个方法,该方法会覆盖父类的同名方法,但有时,我们希望能同时实现父类的功能,这时,我们就需要调用父类的方法了,可以使用super来实现:

class Information(object):
    def __init__(self,name,age):
        self.name = name
        self.age = age

    def print_Flag(self):
        print("我是老大")

class Job_Information(Information):
    def __init__(self,name,age,job_time):
        # Information.__init__(self,name,age)
        super(Job_Information,self).__init__(name,age)
        self.job_time = job_time

    def print_Flag(self):
        super(Job_Information,self).print_Flag()  #super以自己作为参数,调用父类的方法
        print("我是老二")


kebi = Job_Information("科比",25,3)
kebi.print_Flag()

打印结果:

我是老大
我是老二

在上面,我们重新定义了print_Flag方法,一般情况下会打印自己定义的,为了能够实现父类的功能,我们又使用super调用了父类的方法。

二、深入super()

来看一个稍微复杂一点的例子:


class D(object):
def __init__(self):
print("D")

class C(D):
def __init__(self):
print("C")
super(C,self).__init__()

class B(D):
def __init__(self):
print("B")
super(B,self).__init__()

class A(B,C):
def __init__(self):
print("A")
super(A, self).__init__()
# print("B") #将其替换掉,就是这样的
# print("C") #
# print("D")
 

打印的结果:

A
B
C
D

在多继承中,super不只是寻找当前的父类,而是依据mro顺序,根据广度优先查找下一个类。

原文地址:https://www.cnblogs.com/yangmingxianshen/p/7881901.html