2009-04-20 49 views
2

我試圖覆蓋__init__方法,但是當我調用super方法時,在該方法中創建的屬性不可用。 我可以看到它不是繼承問題,因爲class B仍然有可用的屬性。覆蓋__init__時屬性不可用?

我覺得代碼示例將解釋它更好:-)

Python 2.5.2 (r252:60911, Oct 5 2008, 19:24:49) 
[GCC 4.3.2] on linux2 
Type "help", "copyright", "credits" or "license" for more information. 
>>> class A(object): 
... def __init__(self, *args, **kwargs): 
...  self.args = args 
...  self.kwargs = kwargs 
... 
>>> a = A('a', 'b', key='value') 
>>> print a.args, a.kwargs 
('a', 'b') {'key': 'value'} 
>>> class B(A): 
... pass 
... 
>>> b = B('b', 'c', key_b='value_b') 
>>> print b.args, b.kwargs 
('b', 'c') {'key_b': 'value_b'} 
>>> class C(A): 
... def __init__(self, *args, **kwargs): 
...  print 'class C' 
...  super(A, self).__init__(*args, **kwargs) 
... 
>>> c = C('c', 'd', key_c='value_C') 
class C 
>>> print c.args, c.kwargs 
Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
AttributeError: 'C' object has no attribute 'args' 
>>> class D(A): 
... def __init__(self, *args, **kwargs): 
...  super(A, self).__init__(*args, **kwargs) 
...  print 'D' 
... 
>>> d = D('d', 'e', key_d='value D') 
D 
>>> print d.args, d.kwargs 
Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
AttributeError: 'D' object has no attribute 'args' 
>>> 

回答

5

您對超類調用需要使用自己的類型

super(D, self).__init__(*args,**kwargs) 

而不是

super(A... 

我相信調用super(A, self).__init__將調用A的超類,即object。相反,您想調用D的超類,即A

3

您正在使用super()不正確。在您的「C」類的init()方法的第二行應該通過C作爲像這樣的第一個參數...

super(C, self).__init__(*args, **kwargs) 

而且真的,你不應該甚至需要超級這裏使用。您可以致電

A.__init__(self, *args, **kwargs)