Static variable vs Class variable

Bruno Desthuilliers bdesth.quelquechose at free.quelquepart.fr
Sat Oct 6 03:05:54 EDT 2007


Marc 'BlackJack' Rintsch a écrit :
> On Tue, 09 Oct 2007 18:08:34 +0000, Steven D'Aprano wrote:
> 
> 
>>>>>L = []
>>>>>id(L)
>>
>>3083496716L
>>
>>>>>L += [1]
>>>>>id(L)
>>
>>3083496716L
>>
>>It's the same L, not rebound at all.
> 
> It *is* rebound.  To the same object, but it *is* assigned to `L` and not
> just mutated in place.
> 
> In [107]: class A:
>    .....:     a = list()
>    .....:
> 
> In [108]: class B(A):
>    .....:     pass
>    .....:
> 
> In [109]: B.a += [42]
> 
> In [110]: A.a
> Out[110]: [42]
> 
> In [111]: B.a
> Out[111]: [42]
> 
> If it was just mutation then `B.a` would have triggered an `AttributeError`.

Nope.

 >>> class A:
...     l = []
...
 >>> class B(A): pass
...
 >>> A.l
[]
 >>> A.l += [1]
 >>> A.l
[1]
 >>> B.l
[1]
 >>>
 >>> B.l is A.l
True


And it is *not* rebound:

 >>> B.l += [2]
 >>> A.l
[1, 2]
 >>> B.l
[1, 2]
 >>> A.l is B.l
True
 >>>



More information about the Python-list mailing list