Python: super and __init__() vs __init__( self )

16

A:

super( BasicElement, self ).__init__()

B:

super( BasicElement, self ).__init__( self )

A和B有什么区别?我遇到的大多数例子都使用A,但我遇到一个问题,A没有调用父__init__函数,而B却有。这可能是为什么?在哪些情况下应该使用哪一个?


1
展示 B 能够正常运行的代码。什么是 "A 没有被调用" 的意思?你是否遇到了错误?发生了什么事情?除了 self 以外,A.__init__ 是否还带有其他参数? - agf
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    

6
这个构造的重要之处在于,超类A必须显式地从object派生。如果只声明“class A:”,在调用超类的init函数时会引发异常“TypeError: must be type, not classobj”。 - parvus
类A必须派生自Object!!!类A必须派生自Object!!!类A必须派生自Object!!!重复三次以作通知。 - bourneli

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接