内置函数super()
有助于 python 中的继承。该函数返回一个表示父类的对象,并允许访问父类的方法和属性。
**super()**
它不需要任何参数。这个方法可以处理多个继承,并且它避免了显式使用基类名称。
此方法不返回任何内容。在 python 中,方法解析顺序(MRO)概述了方法的继承顺序。派生调用中的方法总是在基类的方法之前调用。
super()
方法的示例super()
在 python 中是如何工作的 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.
super()
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.