Problem with class variables

Thomas Krüger newsgroups at nospam.nowire.org
Thu Mar 29 10:07:34 EDT 2007


Dag schrieb:
> I have a problem which is probaly very simple to solve, but I can't
> find a nice solution.
> I have the following code 
> 
> class Test:
>     def __init__(self):
>         self.a=[1,2,3,4]
>         self.b=self.a
>     def swap(self):
>         self.a[0],self.a[3]=self.a[3],self.a[0]
>     def prnt(self):
>         print self.a
>         print self.b
> c=Test()
> c.swap()
> c.prnt()
> 
> which returns 
> [4,2,3,1]
> [4,2,3,1]
> 
> Now I understand why it is doing this, but it's not what I want.  How to
> I get it to return
> [4,2,3,1]
> [1,2,3,4]
> 
> Dag 

Use a copy of self.a:
self.b = self.a[:]

Thomas



More information about the Python-list mailing list