super()内置方法的使用

1 引入

  • Python 3.x 和 Python 2.x 的一个区别是

    Python 3 可以使用直接使用 super().xxx 代替 super(Class, self).xxx

  • super() 函数是用于调用父类(超类)的一个方法。

  • super() 是用来解决多重继承问题的,直接用类名调用父类方法在使用单继承的时候没问题,但是如果使用多继承,会涉及到查找顺序(MRO)、重复调用(钻石继承)等种种问题。

2 语法

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

3 实用

class Father:
    
    def __init__(self):
        self.name = 'Zoe'
        self.age = 18

    def active(self):
        print('%s今年%d岁' % (self.name, self.age))
        print(self)


class Son(Father):
    
    def __init__(self):
        # super() 首先找到 Son 的父类(就是类 Father),然后把类 Son 的对象转换为类 Father 的对象
        super().__init__()

    def active(self):
        # 调用父类中的方法
        super().active()
        print(self)

s = Son()
print(s.name, s.age)
s.active()

'''
Zoe 18
Zoe今年18岁
<__main__.Son object at 0x000001C413B87D88>
<__main__.Son object at 0x000001C413B87D88>
'''
原文地址:https://www.cnblogs.com/mapel1594184/p/14524928.html