品易云推流 关闭
文章详情页
文章 > Python基础教程 > python中super的使用注意

python中super的使用注意

头像

小妮浅浅

2021-05-14 09:36:052455浏览 · 0收藏 · 0评论

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电脑。

关注

关注公众号,随时随地在线学习

本教程部分素材来源于网络,版权问题联系站长!

底部广告图