Python:super 和 __init__() 与 __init__(self)的区别

16 投票
1 回答
23461 浏览
提问于 2025-04-17 03:33

A:

super( BasicElement, self ).__init__()

B:

super( BasicElement, self ).__init__( self )

A和B有什么区别呢?我看到的大部分例子都用的是A,但我遇到一个问题,就是A没有调用父类的__init__函数,而B却调用了。这是为什么呢?在什么情况下应该使用A,什么情况下又应该使用B呢?

1 个回答

25

你不需要使用第二种形式,除非BasicElement类的__init__方法需要一个参数。

class A(object):
    def __init__(self):
        print "Inside class A init"

class B(A):
    def __init__(self):
        super(B, self).__init__()
        print "Inside class B init"

>>> b = B()
Inside class A init
Inside class B init

或者对于那些需要初始化参数的类:

class A(object):
    def __init__(self, arg):
        print "Inside class A init. arg =", arg

class B(A):
    def __init__(self):
        super(B, self).__init__("foo")
        print "Inside class B init"

>>> b = B()
Inside class A init. arg = foo
Inside class B init    

撰写回答