答:的Python:超級__init __()與__init __(個體經營)
super(BasicElement, self).__init__()
B:
super(BasicElement, self).__init__(self)
是什麼A和B之間有什麼區別?我運行的大多數示例都使用A,但是我遇到了A不調用父__init__函數但B是的問題。爲什麼會這樣呢?哪些應該使用,哪些情況下?
答:的Python:超級__init __()與__init __(個體經營)
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
或與需要初始化參數類:
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
顯示其中'B'工作的代碼。 「'A'沒有調用」是什麼意思?你有錯誤嗎?怎麼了? 'A .__ init__'是否帶有'self'以外的參數? – agf