Problem with class variables

D

Dag

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
 
M

Marc 'BlackJack' Rintsch

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
self.b = list(self.a)

BTW this is about instance variable, not class variables.

Ciao,
Marc 'BlackJack' Rintsch
 
K

kyosohma

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

self.b = list(self.a)

BTW this is about instance variable, not class variables.

Ciao,
Marc 'BlackJack' Rintsch

One of the many ways to do this:

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]
return self.a
def prnt(self):
print self.a
x = self.swap()
print x

c=Test()
c.prnt()


Mike
 
?

=?ISO-8859-15?Q?Thomas_Kr=FCger?=

Dag said:
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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,989
Messages
2,570,207
Members
46,782
Latest member
ThomasGex

Latest Threads

Top