class attribute confusion
OAN
programming at toomuchcookies.net
Fri Dec 3 16:54:19 EST 2010
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!
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)!!
Could someone explain this to me, please?
regards.
More information about the Python-list
mailing list