super()函数是用于调用父类的一个方法. 举个例子:
执行下面代码时, 会显示 Son 类没有属性 money
- class Father:
- def __init__(self):
- self.money = 1000class Son(Father):
- def __init__(self):
- self.age = 10
- def show_father_money(self):
- print(self.money)
- a = Son()
- a.show_father_money() # 执行出错, 显示 AttributeError: 'Son' object has no attribute 'money'
所以如果没有用构造方法[__init__] 初始化父类的值就无法调用相应属性, 这时候我们可以将代码改为:
- class Father(object):
- def __init__(self):
- self.money = 1000
- class Son(Father):
- def __init__(self):
- Father.__init__(self) # 调用父类构造函数
- self.age = 10
- def show_father_money(self):
- print(self.money)
- a = Son()
- a.show_father_money() # 1000
这样就可以正常执行了, 但是在实际运用中, 由于子类继承的父类可能会改变名字, 并且子类可能不止只继承一个父类, 所以出于方便的角度考虑, 我们就可以调用 super()方法, super()方法通过 MRO 列表 [可通过打印 Son.mro() 查看] 来解决多重继承问题. super()可自动查询并执行 MRO 列表中父类相应的方法.
- class GrandFather(object):
- def __init__(self):
- self.money1 = 1000
- class Father(GrandFather):
- def __init__(self):
- super().__init__()
- self.money2 = 2000
- class Son(Father):
- def __init__(self):
- super().__init__()
- self.age = 10
- def show_father_money(self):
- print(self.money1)
- print(self.money2)
- a = Son()
- a.show_father_money() # 1000 2000
python super()函数
来源: http://www.bubuko.com/infodetail-3073247.html