开发者

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

A:

super( BasicElement, self ).__init__()

B:

super( BasicElement, self ).__init__( self )

What is the difference between A and B? Most examples that I run across use A, but I am running into an issue where A is not calling the parent __init__ function, but B is. Why might this be? Which should be used and in which case开发者_如何学Pythons?


You should not need to do that second form, unless somehow BasicElement class's __init__ takes an argument.

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

Or with classes that need init arguments:

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    
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜