天天看点

七、面向对象_6.super()

super()

super(当前类名,self).func() / super().func()
        功能:调用父类方法

super()可以自动查找父类,调用遵循__mro__类属性的顺序,比较适合单继承使用
           
class Ronaldinho(object):
    def __init__(self):
        self.skill = '牛尾巴'

    def play_soccer(self):
        print(f'技能:{self.skill}')

class Messi(Ronaldinho):
    def __init__(self):
        self.skill = '油炸丸子'

    def play_soccer(self):
        print(f'技能:{self.skill}')

        # 方法二:super()
        # 1.super(当前类名,self).func()
        # super(Messi,self).__init__()
        # super(Messi,self).play_soccer()

        # 2.super(当前类名,self).func()
        super().__init__()
        super().play_soccer()

class Neymar(Messi):
    def __init__(self):
        self.skill = '彩虹'

    def play_soccer(self):
        self.__init__()
        print(f'技能:{self.skill}')

    def play_ronaldinho_soccer(self):
        Ronaldinho.__init__(self)
        Ronaldinho.play_soccer(self)

    def play_messi_soccer(self):
        Messi.__init__(self)
        Messi.play_soccer(self)

    # 一次性调用父类同名属性和方法
    def play_old_soccer(self):

        # 方法一:
        # 缺点:1.如果父类名更改,此处也需要修改  2.如果父类很多则代码量过大
        # Ronaldinho.__init__(self)
        # Ronaldinho.play_soccer(self)
        # Messi.__init__(self)
        # Messi.play_soccer(self)

        # 方法二:super()
        # 1.super(当前类名,self).func()
        # super(Neymar,self).__init__()
        # super(Neymar,self).play_soccer()

        # 2.super().func()
        super().__init__()
        super().play_soccer()

N = Neymar()
# N.play_soccer()
# N.play_ronaldinho_soccer()
# N.play_messi_soccer()
# N.play_soccer()
N.play_old_soccer()

技能:油炸丸子
技能:牛尾巴
           

继续阅读