我試圖覆蓋__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'
>>>