4

My code:

 class World:
 def __init__(self, _map, pos):
 self.orig_map = _map
 self.map = self.orig_map[:]
 self.orig_pos = pos
 self.pos = list(self.orig_pos)
 def reset(self):
 self.map = self.orig_map[:]
 self.pos = list(self.orig_pos)
 def left(self):
 if self.pos[1]>0:
 self.pos[1]-=1
 def right(self):
 if not self.pos[1]+1>=len(self.map[0]):
 self.pos[1]+=1
 def up(self):
 if self.pos[0]>0:
 self.pos[0]-=1
 def down(self):
 if not self.pos[0]+1>=len(self.map):
 self.pos[0]+=1
 def eat(self):
 if self.map[self.pos[0]][self.pos[1]]==1:
 self.map[self.pos[0]][self.pos[1]]=0
 return True

What is supposed to happen:

>>> w=World([[0,0,0],[0,1,0],[0,0,0]],(0,0))
>>> w.right()
>>> w.down()
>>> w.eat()
True
>>> w.reset()
>>> w.map
>>> [[0, 0, 0], [0, 1, 0], [0, 0, 0]]

What happens:

>>> w=World([[0,0,0],[0,1,0],[0,0,0]],(0,0))
>>> w.right()
>>> w.down()
>>> w.eat()
True
>>> w.reset()
>>> w.map
>>> [[0, 0, 0], [0, 0, 0], [0, 0, 0]]

Where it probably goes wrong: self.map = self.orig_map[:]

The above would have worked (tried and tested) for a single list, however, it doesn't seem to work for nested lists.

asked May 30, 2017 at 13:01
5
  • 4
    deep_copy it. See this Commented May 30, 2017 at 13:03
  • Did you mean w.orig_map in the last step? You could in this case use the copy module's deepcopy function. Commented May 30, 2017 at 13:04
  • @IljaEverilä No, I meant w.map. However, at that step, they should be equal (value wise) but be different objects. Commented May 30, 2017 at 13:07
  • 1
    Right, missed the reset() call. Commented May 30, 2017 at 13:09
  • Depending on exactly what self.orig_map contains, deepcopy may not work stackoverflow.com/questions/1601269/… Commented May 30, 2017 at 13:18

2 Answers 2

6

By saying self.map = self.orig_map[:] you are indeed making a copy of self.orig_map. However, this is a shallow copy, and the elements within self.map will still be the same objects as the elements within self.orig_map.

What you need to do instead is make self.map a deep copy of self.orig_map in your __init__. E.g.

import copy
...
 self.map = copy.deepcopy(self.orig_map)
answered May 30, 2017 at 13:05
4

You should use deepcopy

import copy
cop2 = copy.deepcopy(origin) 

It will recursively copy your object.

answered May 30, 2017 at 13:04

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.