• 技术文章 >Python技术 >Python基础教程

    python中super的使用注意

    小妮浅浅小妮浅浅2021-05-14 09:36:05原创2226

    1、super()只能用于新式类中

    所谓新式类,旧类的,关键就是看是不是有基类,有基类的就是形式类,比如class A(object),所以class A()自然就是旧式类了。

    # 单继承
    class A(object):
     
        def __init__(self, a, b):
            self.a = a
            self.b = b
     
        def sayHello(self):
            print('this is class A, a={},b={}'.format(self.a, self.b))
     
    class B(A):
     
        def __init__(self, a, b, c):
            super(B, self).__init__(a,b)
            self.c = c
     
        def sayHello(self):
            super(B, self).sayHello()
            print('this is b call')
     
    b = B('b','also b','test')
    b.sayHello()
    # this is class A, a=b,b=also b
    # this is b call

    2、super 其实和父类没有实质性的关联

    多重继承下,super就没有那么简单了。

    # 多重继承
     
    class Base(object):
        def __init__(self):
            print('enter Base')
            print('out Base')
    class A(Base):
        def __init__(self):
            print('enter A')
            super(A, self).__init__()
            print('out A')
    class B(Base):
        def __init__(self):
            print('enter B')
            super(B, self).__init__()
            print('out B')
    class C(A, B):
        def __init__(self):
            print('enter C')
            super(C, self).__init__()
            print('out C')
     
    c = C()
    #enter C
    #enter A
    #enter B
    #enter Base
    #out Base
    #out B
    #out A
    #out C

    以上就是python中super的使用注意,希望能对大家有所帮助。更多Python学习指路:python基础教程

    本文教程操作环境:windows7系统、Python 3.9.1,DELL G3电脑。

    专题推荐:python super
    品易云
    上一篇:python创建和使用堆的方法 下一篇:python如何在自定义类上使用堆排序

    相关文章推荐

    • python super().__init__()• python中super()和父类关系• java中this和super相同和不同分析• python中super获取类变量

    全部评论我要评论

    © 2021 Python学习网 苏ICP备2021003149号-1

  • 取消发布评论
  • 

    Python学习网