python中super的使用注意

439次阅读
没有评论

python中super的使用注意

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的使用注意,希望能对大家有所帮助。

神龙|纯净稳定代理IP免费测试>>>>>>>>天启|企业级代理IP免费测试>>>>>>>>IPIPGO|全球住宅代理IP免费测试

相关文章:

版权声明:wuyou2021-05-03发表,共计1127字。
新手QQ群:570568346,欢迎进群讨论 Python51学习