五分钟读懂Python中super().__init__和Base.__init__的区别

371次阅读
没有评论

五分钟读懂Python中super().__init__和Base.__init__的区别

我们在使用python中的类继承时,子类继承父类后,在重载父类的方法后,在方法中如果要执行父类对应的方法,一般有两种方式:super和Base(表示父类名)。

使用例子

先看下面一段代码:

# -*- coding: utf-8 -*-class Base:
    def __init__(self):
        self.postion = (0, 0)    def move(self, x, y):
        self.postion = (self.postion[0] + x, self.postion[1] + y)class Device(Base):
    def __init__(self):
        super(Device, self).__init__()
        self.offset = (0, 0)    # 记录本次位置偏移量
    def move(self, x, y):
        self.offset = (self.postion[0] - x, self.postion[1] - y)
        super(Device, self).move(x, y)        
    def get_offset(self):
        return self.offset

在Base类中,有一个move方法用来移动位置,在子类中我们想要增加一个记录,记住每次移动的偏移量,那么我们就在子类中重载move函数,执行我们自定义的操作(记录偏移量),然后继续执行父类的move动作,直接调用父类move函数就可以避免我们重新实现移动位置的动作。

在上面的例子中,我们使用了super来调用父类方法,那么能不能使用Base来调用呢?

....
Base.__init__(self)
......
Base.move(self, x, y)
....

可以看到Base调用父类函数时,必须在函数中传递self参数。之前的文章中我们了解到类的普通函数调用需要使用类对象调用,而类的普通函数第一个参数默认是self,调用时不需要传递此参数,因为通过对象调用会自动传递。但是直接使用Base类名调用时,方法内部需要知道self是谁。那么两种方式都可以,他们有区别吗?当然是有的

首先看一下super的定义

class super(object):
    """
    super() -> same as super(__class__, <first argument>)
    super(type) -> unbound super object
    super(type, obj) -> bound super object; requires isinstance(obj, type)
    super(type, type2) -> bound super object; requires issubclass(type2, type)
    Typical use to call a cooperative superclass method:
    class C(B):
        def meth(self, arg):
            super().meth(arg)
    This works for class methods too:
    class C(B):
        @classmethod
        def cmeth(cls, arg):
            super().cmeth(arg)
    """

可以看到,super有四种调用方式

super(): 相当于super(当前类名, 第一个参数)      python3中新增的方式

super(type):没有绑定对象

super(type, obj):绑定对象,要求obj的类型是type或者其子类

super(type, type2):绑定对象,要求type2是type的子类

这里我们就先说一下super()和super(type, obj),这是我们常用的方式

在上面的例子中我们看到super和Base的方式一样,接下来我们再看一个例子

# -*- coding: utf-8 -*-class Base:
    def __init__(self):
        print("Base")
        self.name = "Base"class Device1(Base):
    def __init__(self):
        Base.__init__(self)
        print("Device1")
        self.name1 = "Device1"class Device2(Base):
    def __init__(self):
        Base.__init__(self)
        print("Device2")
        self.name2 = "Device2"class Sub(Device1, Device2):
    def __init__(self):
        Device1.__init__(self)
        Device2.__init__(self)
        print("Sub")
        self.name3 = "Sub"

    def test(self):
        print("test: ", self.name2)

s = Sub()
s.test()# 输出:Base                #Base.__init__中的printDevice1           
#Device1.__init__中的printBase                #Base.__init__中的printDevice2           
#Device2.__init__中的printSub                  #Sub.__init__中的printtest:  Device2  #test方法中的print

四个类,Base初始化函数被调用了两次,为什么呢?Sub.__init__中Device1和Device2都调用了初始化方法,是这个原因吗?准确点来讲,是的,可不可以只调用一个,那么Base就只会被调用一次喽,如果只调用Device1.__init__会有什么结果?

Base
Device1
Sub
Traceback (most recent call last):
  File "/Users/small_bud/Desktop/Python/SpiderProjects/淘宝搜索/__init__.py", line 30, in <module>
    s.test()
  File "/Users/small_bud/Desktop/Python/SpiderProjects/淘宝搜索/__init__.py", line 27, in test
    print("test: ", self.name2)
AttributeError: 'Sub' object has no attribute 'name2'

没有name2属性,而且Device2的初始化函数__init__没有调用,所以name2属性没有被定义,那如果把Base换成super,结果怎么样呢?

# -*- coding: utf-8 -*-class Base:
    def __init__(self):
        print("Base")
        self.name = "Base"class Device1(Base):
    def __init__(self):
        super().__init__()
        print("Device1")
        self.name1 = "Device1"class Device2(Base):
    def __init__(self):
        super().__init__()
        print("Device2")
        self.name2 = "Device2"class Sub(Device1, Device2):
    def __init__(self):
        super().__init__()
        print("Sub")
        self.name3 = "Sub"

    def test(self):
        print("test: ", self.name2)

s = Sub()
s.test()# 输出:Base               #Base.__init__中的printDevice2           
#Device2.__init__中的printDevice1           #Device2.__init__中的printSub                  
#Sub.__init__中的printtest:  Device2   #test方法中的print

我们类的每一个函数首地址会被存储起来,当我们用类名去调用一个函数的时候,我们可以理解为它代表一个绝对的地址,可以绝对定位到函数的地址。这个时候你可以把它理解为一个普通函数def Base.__init__(self),函数名是Base.__init__,参数是self

# 这是一个测试类,只为创建一个空对象class Test:
    passclass Base:
    def __init__(self):
        self.name = "aaaa"def func(obj):
    obj.age = 111t = Test()
Base.__init__(t)
print(t.name)
func(t)
print(t.age)#输出:aaaa111

看到了,Base.__init__和func是一样的,这绝不是我们所希望的类函数。那么为什么super会正确的找到要执行的函数呢?看一下下面的例子:

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

D()
print(D.mro())#输出:A
B
C
D
[<class '__main__.D'>, <class '__main__.C'>, <class '__main__.B'>, <class '__main__.A'>, <class 'object'>]

我们知道子类的对象初始化时,将先执行父类的初始化,然后才执行子类初始化,从初始化打印信息也可以看出来,A>B>C>D,再看一下mro()函数的打印信息,这里展示了当前类及其父类的类名,我们可以这样理解每一个类被定义后,其存储在程序存储区,除了类方法,还存在一个继承管理表,表中按照一定的顺序存储着类及其父类的类名,类的初始化就按照表中的顺序进行初始化,按照以上的顺序object>A>B>C>D,从object开始初始化,然后是A、B、C、D。之前Base.__init__的调用我们分析过了,现在super这种方式呢?它是根据mro列表中记录的类,按照顺序依次调用,这样就不会出现一个类被重复调用的情况。MRO列表是通过一种算法计算出顺序的,我们不用关注它,不过要记住以下几个准则:

子类会先于父类被检查

子类一定是在列表的第一位

多个父类会根据它们在列表中的顺序被检查

C继承自A、B,A和B哪个先被调用,根据他们在表中的顺序

如果对下一个类存在两个合法的选择,选择第一个父类

总结

通过上面的分析,我们知道在类继承中,一定要使用super的方式才能正确调用类继承关系,在python3中推荐使用super().__init__,pytho2中使用super(Base, self).__init__。

神龙|纯净稳定代理IP免费测试>>>>>>>>天启|企业级代理IP免费测试>>>>>>>>IPIPGO|全球住宅代理IP免费测试

相关文章:

版权声明:wuyou2021-07-05发表,共计5292字。
新手QQ群:570568346,欢迎进群讨论 Python51学习