Class with subclass and dynamic lists
Emile van Sebille
emile at fenx.com
Thu Jul 26 09:03:48 EDT 2001
I don't know exactly what you're trying to do here, but you are creating
instances that share class attributes. Consider for example:
class Temp:pass
class A:
attr = Temp()
class B:
def __init__(self):
self.attr = Temp()
a,b,c = A(), A(), A()
print id(a.attr)
print id(b.attr)
print id(c.attr)
a,b,c = B(), B(), B()
print id(a.attr)
print id(b.attr)
print id(c.attr)
Moving Temp() to the __init__ method in class B causes the instances to each
have their own new Temp instance. In class A all instances share the class
copy of attr until/unless you specifically assign to it using something
like:
a = A()
a.attr = Temp()
HTH,
--
Emile van Sebille
emile at fenx.com
---------
"Piotr Legiecki" <piotrlg at sci.pam.szczecin.pl> wrote in message
news:3B600A64.EC187E9 at sci.pam.szczecin.pl...
> Hi
>
> I can't resolve my problem. Here is the test code
>
> class A:
> x=[] #it will be list of B objects
> z=None #something, doesn't matter
>
> class B:
> y=None
>
>
> #this function adds to A object (arg) B objects with value val
> def f(arg, val):
> for i in range(1,3): #to put some values into the list
> arg.x.append(B())
> l=len(arg.x)-1 #well, it is just added the last object in a
> list,
> arg.x[l].y=val+i #assign him somethig
> print 'in f', arg.x[l].y # test
> print l #test, here I can see, that my list in
> class A (x[]) is THE SAME for all the
> #A instances! Why?
>
> def main():
> p=[] #list of class A objects
> p.append(A()) #make 2 objects of class A
> f(p[0], 10) #send object A, from list of A's objects (I hope) to add
> a list of B objects to A object
> p[0].z='aaa'
>
> p.append(A()) #second A object
> p[1].z='bbb'
> f(p[1],20)
>
> #testing, not good
> print p[0].x[0].y
> print p[0].x[1].y
> print p[0].z
> print p[1].x[0].y #here I have the same values as in p[0].x[0].y, why?
> print p[1].x[1].y #why p[1].x is the same list for both (p[0], p[1]) A
> objects?
> print p[1].z
> print p[0].z
>
> main()
>
> --
> Regards
> Piotr Legiecki
More information about the Python-list
mailing list