Python面向对象_super()函数

super()

super()是用于**调用父类(超类)**的一个方法

用于解决多重继承问题:直接用类名调用父类方法在使用单继承时没有问题,但若使用多继承,会涉及到查找顺序(MRO)、重复调用(钻石继承)等问题

MRO 就是类的方法解析顺序表, 其实也就是继承父类方法时的顺序表。

语法

super(type[, object-or-type])

参数

  • type

  • object-or-type 类,一般是self

在 Python3 中:super().xxx

在 Python2 中:super(Class, self).xxx

两者等价

示例

class Bird:
    def __init__(self):
          self.hungry = True
    def eat(self):
          if self.hungry:
               print('Ahahahah')
          else:
               print('No thanks!')

class SongBird(Bird):
     def __init__(self):
          self.sound = 'Squawk'
     def sing(self):
          print(self.sound)

sb = SongBird()
sb.sing()    # 能正常输出'Squawk'
sb.eat()     # 报错,因为 SongBird 中没有 hungry 特性

使用super解决:

class SongBird(Bird):
    def __init__(self):
        super().__init__()
        self.sound = 'squawk'
    def sing(self):
        print(self.sound)

它会查找所有的超类,以及超类的超类,直到找到所需的特性为止

Licensed under CC BY-NC-SA 4.0
comments powered by Disqus