super()函数主要是用来调用父类(单继承时),在多继承时会涉及MRO顺序问题。
https://www.runoob.com/w3cnote/python-super-detail-intro.html
https://www.runoob.com/python/python-func-super.html
class A():
def __init__(self,name):
print('A的__init__()')
self.name = name
def p(self):
print(self.name)
class B(A):
def __init__(self):
# 继承的时候,父类的初始话参数也得传进去
super(B,self).__init__(name=None)
# 子类自己的__init__()没有参数,所以实例化时候不用传进去
b = B()
#super()继承之后,把父类的方法也继承下来。
b.p()
A的__init__()
None
class A():
def __init__(self,name):
print('A的__init__()'+'\n')
self.name = name
def p(self):
print(self.name)
class B(A):
def __init__(self,name):
super(B,self).__init__(name=None)
# 属性覆盖
self.name = name
# 函数覆盖
def p(self):
print('B的p()函数')
print('name:',self.name)
c = B('c')
c.p()
A的__init__()
B的p()函数
name: c
class A():
def __init__(self,name):
print('A的__init__()'+'\n')
self.name = name
def p(self):
print(self.name)
class B(A):
def __init__(self,name):
self.name = name
# 继承也会覆盖属性
super(B,self).__init__(name=None)
def p(self):
print('B的p()函数')
print('name:',self.name)
c = B('c')
c.p()
A的__init__()
B的p()函数
name: None