内置函数 super() 帮助 Python 中的继承。此函数返回一个表示父类的对象,并提供对父类方法和属性的访问。
super()
它不接受任何参数。此方法可以与多重继承一起使用,并且避免了显式使用基类名称。
此方法不返回任何内容。在 Python 中,方法解析顺序 (MRO) 概述了方法继承的顺序。派生类中的方法始终在基类方法之前调用。
class Mammals(object):
def __init__(self, mammalName):
print(mammalName, 'is a pet animal.')
class Cat(Mammals):
def __init__Cat has four legs.')
super().__init__('Cat')
c = Cat()
输出
Cat is a pet animal.
class Animals:
def __init__(self, Animals):
print(Animals, 'is an animal.');
class Mammals(Animals):
def __init__(self, mammalName):
print(mammalName, 'is a pet animal.')
super().__init__(mammalName)
class NonWingedMammal(Mammals):
def __init__(self, NonWingedMammal):
print(NonWingedMammal, "can't fly.")
super().__init__(NonWingedMammal)
class NonMarineMammal(Mammals):
def __init__(self, NonMarineMammal):
print(NonMarineMammal, "can't swim.")
super().__init__(NonMarineMammal)
class Cat(NonMarineMammal, NonWingedMammal):
def __init__(self):
print('Cat has 4 legs.');
super().__init__('Cat')
c = Cat()
print('')
bat = NonMarineMammal('Bat')
输出
Cat has 4 legs. Cat can't swim. Cat can't fly. Cat is a pet animal. Cat is an animal. Bat can't swim. Bat is a pet animal. Bat is an animal.