class attribute confusion

Omar Abo-Namous kontakt at toomuchcookies.net
Sat Dec 4 09:00:43 EST 2010


Am 03.12.2010 23:11, schrieb Arnaud Delobelle:
> OAN<programming at toomuchcookies.net>  writes:
>
>> Hi,
>>
>> i was having a problem with class attributes initiated outside of
>> __init__. This code is a demonstration of what i mean:
>>
>> class A():
>>      mylist = []
>>      def __init__(self):
>>          self.mylist.append(1)
>>          pass
>>
>> class B(A):
>>      def __init__(self):
>>          A.__init__(self)
>>          self.mylist.append(2)
>>
>> v = A()
>> print 'v:',v.mylist
>> x = B()
>> print 'x:',x.mylist
>> y = B()
>> print 'y:',y.mylist
>> z = A()
>> print 'z:',z.mylist
>> print 'v:',v.mylist
>>
>> I would expect the following result:
>>
>> v: [1]
>> x: [1, 2]
>> y: [1, 2]
>> z: [1]
>> v: [1]
>>
>> Who wouldn't, right? But actually python 2.6(.6) gives me the
>> following result:
>>
>> v: [1]
>> x: [1, 1, 2]
>> y: [1, 1, 2, 1, 2]
>> z: [1, 1, 2, 1, 2, 1]
>> v: [1, 1, 2, 1, 2, 1]
>>
>> The four variables v,x,y and z now actually share the same 'mylist'!!
>> To get the correct results, i have to initialize 'mylist' inside of
>> the __init__ method!
> Yes.  See below.
>
>> I think this behaviour is totally wrong, since it seems
>> A.__init__(self) is changing the value inside of A() not inside of the
>> object variable 'self' (that should be x or y)!!
> It's not wrong at all.  You expect "mylist" to behave as an instance
> attribute, but you defined it as a class attribute.  Instance attributes
> are naturally initialised in the __init__() method.
>
Could you please point me to a reference in the doc??

Thanks in advance.





More information about the Python-list mailing list