python中super的使用注意

2025-12-01 0 49,771

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

收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

声明:以上部本文内容由互联网用户自发贡献,本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。投诉邮箱:3758217903@qq.com

ZhiUp资源网 python基础 python中super的使用注意 https://www.zhiup.top/2157.html

相关