1.简介
语法:super(type[, object-or-type])
参数 | 描述 |
---|
type:类名
object-or-type:self(实例对象)或cls(类对象)
主要使用场景有两种:
1.对象
2.类
在python3
中可以简写成super()
,而不必输入参数。
2.对象中的使用
super(类名,self)返回父类实例
2.1调用父类方法
super()
方法返回该类的父类
class A(object):
def func(self):
print("funA")
class B(A):
def func(self):
print("funB")
test = B()
test.func()# funB
class A(object):
def func(self):
print("funA")
class B(A):
def func(self):
# print("funB")
super(B,self).func() # super() 返回父类A,然后调用A的func方法.(B,self)在python3中是默认值,不需要填写.B是指本类名,不能用cls代替,self是本类实例化的对象
test = B()
test.func()
super的本质,并非是父类,而是遍历所有父,如下菱形继承:
class Base(object):
def __init__(self):
print("enter Base")
print("leave Base")
class A(Base):
def __init__(self):
print("enter A")
super(A, self).__init__()
print("leave A")
class B(Base):
def __init__(self):
print("enter B")
super(B, self).__init__()
print("leave B")
class C(A, B):
def __init__(self):
print("enter C")
super(C, self).__init__()
print("leave C")
c = C()
#enter C
#enter A
#enter B # 如果是父类的话,这里由A就应该跳到Base,而并没有
#enter Base
#leave Base
#leave B
#leave A
#leave C
2.2.类中使用
super(类名,cls)
注意这里第二个参数,不是self
而是cls
,这里是调用的类实例。
object.new
总结
无论在对象中使用super(类名,self)
还是在类中使用super(类名,cls)
,在python3中,都可以简写为super()
super的原理:是遍历__mro__
列表
mro
列表遵循:
1)子类永远在父类之前
2)多个父类,根据在列表中的位置检查,选择第一个父类
def super(cls, inst):
mro = inst.__class__.mro()
return mro[mro.index(cls) + 1]
参考:
https://www.cnblogs.com/youleng/p/8696384.html
https://blog.csdn.net/wowocpp/article/details/105223224
https://blog.csdn.net/Leafage_M/article/details/53324641
https://blog.csdn.net/Code_LT/article/details/107034471