开发者

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

开发者 https://www.devze.com 2023-04-10 18:16 出处:网络
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

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

精彩评论

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