基本概念
这三个都是和类相关的概念。 new 和 init是类在实例化过程中执行的函数。 super是在继承的情况下,执行某个被覆盖的程序的一个方法。 (多继承的原则: 广度优先)
- __new__: 实例化时,new一个实例出来的函数。
- __init__: 对new 返回的 实例进行初始化的函数。
- spuer(): 和__mro__ 配套的内容的函数。__mro__是一个list,是super执行顺序的list。
具体例子
1. new 和 init的例子
首先看代码,从代码看本质。
class Test():
def __init__(self,*args,**kargs):
print("__init__ start")
def __new__(cls,*args,**kargs):
print("__new__ start")
return super().__new__(cls,*args,**kargs)
a = Test()
# 下面是print结果
__new__ start
__init__ start
复制代码
2.super的例子
老规矩,看代码. 下面的代码,可以看出,是按照__mro__ 的顺序执行的。
super有两种使用方式,第一,不带任何参数。按照__mro__顺序匹配。 第二,带两个参数的使用方法(type,objce_of_type), 在__mro__中的 参数 type 右边开始匹配。
class A:
def __init__(self):
self.n = 2
def add(self,m):
print("the ne in A is {}".format(self.n))
self.n += m
class B(A):
def __init__(self):
self.n = 3
def add(self,m):
print("BEFORE the ne in B is {}".format(self.n))
super().add(m)
print("AFTER the ne in B is {}".format(self.n))
self.n +=3
class C(A):
def __init__(self):
self.n = 3
def add(self,m):
print("BEFORE the ne in C is {}".format(self.n))
super().add(m)
print("AFTER the ne in C is {}".format(self.n))
self.n +=4
class D(B, C):
def __init__(self):
self.n = 5
def add(self, m):
print('self is {0} @D.add'.format(self.n))
super().add(2)
self.n += 5
d = D()
d.add(2)
print(d.n)
# print result
self is 5 @D.add
BEFORE the ne in B is 5
BEFORE the ne in C is 5
the ne in A is 5
AFTER the ne in C is 7
AFTER the ne in B is 11
19
# __mro__
D.mro()
[<class '__main__.D'>, <class '__main__.B'>, <class '__main__.C'>, <class '__main__.A'>, <class 'object'>]
# super 的用法
def super(cls, inst):
mro = inst.__class__.mro()
return mro[mro.index(cls) + 1]
class C(B):
def method(self, arg):
super().method(arg) # This does the same thing as:
# super(C, self).method(arg)
复制代码