python 中super方法的调用

参考https://www.runoob.com/python/python-func-super.html 加以解释

class FooParent(object):
    def __init__(self):
        self.parent = "I am the parent."
        print('Parent')

    def bar(self, message):
        print("%s from Parent" % message)

class FooChild(FooParent):
    def __init__(self):
        super(FooChild, self).__init__()
        print('Child')

    def bar(self,message):
        # 调用父类的bar方法
        super(FooChild, self).bar(message)

        print('Child bar function')

        # 打印父类的parent
        print(self.parent)

if __name__ == '__main__':
    fooChild = FooChild()
    # fooChild.bar('HelloWorld')
    # 不实例化调用
    # FooChild().bar('Hello World')

结果

子类和父类实例化所答打印的
Parent
Child
父类的bar方法打印
HelloWorld from Parent
子类bar方法打印
Child bar function
父类初始化所给parent变量赋值
I am the parent.
class A():
    def __init__(self):
        print('enter A')
        print('leave A')


class B(A):
    def __init__(self):
        print('enter B')
        super().__init__()
        print('leave B')


class C(A):
    def __init__(self):
        print('enter C')
        super().__init__()
        print('leave C')


class D(B, C):
    def __init__(self):
        print('enter D')
        super().__init__()
        print('leave D')


d = D()

结果

enter D
enter B
enter C
enter A
leave A
leave C
leave B
leave D
发布了250 篇原创文章 · 获赞 17 · 访问量 8万+

猜你喜欢

转载自blog.csdn.net/qq_35899407/article/details/103686444
今日推荐