用法入门
super()就是用来调用父类(超类)的方式。
常用格式
super().method_name
super(type, object).method_name #判断isinstance(object, type)
示例
class Base():
def __init__(self):
print('---我是Base类---')
def run(self, catname):
print('{},跑呀跑'.format(catname))
class Mytest(Base):
def __init__(self):
print('---我是测试类---')
super(Mytest, self).run('狸花猫') #或者super().run('狸花猫')
mytest = Mytest()
-------------
输出:
---我是测试类---
狸花猫,跑呀跑
super(Mytest, self).run('xxx') 可以理解为:
super(Mytest, self).run('xxx') == Base.__init__(self)
进阶解释
单继承时-super()和直接用父类类名调用方法的区别
单继承时,super()和直接用父类类名调用方法没有区别。
super()
class Base():
def __init__(self):
print('---我是Base类---')
class Mytest(Base):
def __init__(self):
super().__init__()
print('---我是测试类---')
mytest = Mytest()
--------------
输出:
---我是Base类---
---我是测试类---
直接父类类名调用方法
class Base():
def __init__(self):
print('---我是Base类---')
class Mytest(Base):
def __init__(self):
Base.__init__(self)
print('---我是测试类---')
mytest = Mytest()
----------------
输出:
---我是Base类---
---我是测试类---
多继承时-super()和直接用父类类名调用方法的区别
super遵从广度优先搜索(MRO),直接父类类名调用方法则调用哪个父类就执行哪个父类。
super()
class A():
def __init__(self):
print('---我是A类---')
class B():
def __init__(self):
print('---我是B类---')
class Mytest(A, B):
def __init__(self):
print('---我是测试类---')
super().__init__()
mytest = Mytest()
-----------
输出:
---我是测试类---
---我是A类---
直接父类类名调用方法
class A():
def __init__(self):
print('---我是A类---')
class B():
def __init__(self):
print('---我是B类---')
class Mytest(A, B):
def __init__(self):
B.__init__(self)
A.__init__(self)
print('---我是测试类---')
mytest = Mytest()
----------------
输出:
---我是B类---
---我是A类---
---我是测试类---
钻石继承时-super()和直接用父类类名调用方法的区别
Base
/ \
/ \
A B
\ /
\ /
C
super()调用顺序:Mytest --> A --> B --> Base
直接父类类名调用方法调用顺序:Mytest --> A --> Base --> B --> Base
钻石继承时,如果不适用super函数,则Base类会被多次调用,增大开销。
super()
class Base():
def __init__(self):
print('---我是Base类---')
class A(Base):
def __init__(self):
print('---我是A类---')
super().__init__()
class B(Base):
def __init__(self):
print('---我是B类---')
super().__init__()
class Mytest(A, B):
def __init__(self):
print('---我是测试类---')
super().__init__()
mytest = Mytest()
----------------
输出:
---我是测试类---
---我是A类---
---我是B类---
---我是Base类---
直接父类类名调用方法
class Base():
def __init__(self):
print('---我是Base类---')
class A(Base):
def __init__(self):
print('---我是A类---')
Base.__init__(self)
class B(Base):
def __init__(self):
print('---我是B类---')
Base.__init__(self)
class Mytest(A, B):
def __init__(self):
print('---我是测试类---')
A.__init__(self)
B.__init__(self)
mytest = Mytest()
----------------
输出:
---我是测试类---
---我是A类---
---我是Base类---
---我是B类---
---我是Base类---
super对比直接通过父类类名调用的优势
- 使用super时,如果类的继承关系发生改变了,只需要修改class定义时的继承关系;而如果使用父类类名直接调用,则需要将类中所有用到父类类名的地方全都替换。
- Python3中super遵循MRO-广度优先原则,且父类只调用一次,避免重复调用。