20201112-super()函数

2020-11-12  本文已影响0人  野山羊骑士

https://www.runoob.com/python/python-func-super.html

描述

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

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

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

参数

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

python3 实例

class A:
     def add(self, x):
         y = x+1
         print(y)
class B(A):
    def add(self, x):
        super().add(x)
b = B()
b.add(2)  # 3
class Test():
    def __init__(self,config):
        self.jlk = config


class Root(Test):
#    def __init__(self):
#        self.x = '这是属性'

    def fun(self):
        print('这是方法')


class A(Root):
    def __init__(self):
        super(A,self).__init__('lhy')
        print('实例化时执行')


test = A()  # 实例化类
test.fun()  # 调用方法
print(test.jlk) # 调用属性
上一篇下一篇

猜你喜欢

热点阅读