[英]Python: super and __init__() vs __init__( self )
A:
super( BasicElement, self ).__init__()
B:
super( BasicElement, self ).__init__( self )
A和B有什么區別? 我遇到的大多數示例使用A,但我遇到的問題是A沒有調用父__init__函數,但是B是。 為什么會這樣? 應該使用哪種情況?
你不應該做那個第二種形式,除非以某種方式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
或者使用需要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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.