I have a doubt about storing a class variables in a second variable, in order to be called later. This is my code (simplified to be readable):
class Agent(object):
def __init__(self):
self.actual = []
class Play(object):
def __init__(self):
self.x = 0.45 * 400
self.y = 0.5 * 400
self.position = []
self.position.append([self.x, self.y])
self.x_change = 20
self.y_change = 0
def do_move(self, move, x, y):
move_array = [self.x_change, self.y_change]
if move == 1 and self.x_change == 0: # right
move_array = [20, 0]
self.x_change, self.y_change = move_array
self.x = x + self.x_change
self.y = y + self.y_change
self.update_position(self.x, self.y)
def update_position(self, x, y):
self.position[-1][0] = x
self.position[-1][1] = y
def run():
agent = Agent()
player1 = Play()
agent.actual = [player1.position]
print(agent.actual[0])
i = 1
player1.do_move(i, player1.x, player1.y)
print(agent.actual[0])
run()
>> [[180.0, 200.0]]
>> [[200.0, 200.0]]
This is what I cannot understand. Why, if agent.actual
stores the player.position
and it is not modified after agent.actual = [player1.position]
, its value actually changes between the two print()
?
I modify player.position
, but not agent.actual
, which means it should stay the same. I cannot figure this out!
EDIT: I tried, as suggested, with the following methods:
agent.actual = player1.position.copy()
agent.actual = player1.position[:]
agent.actual= list(player1.position)
import copy
agent.actual = copy.copy(player1.position)
agent.actual = copy.deepcopy(player1.position)
All these methods always return, as before, two different values:
>> [[180.0, 200.0]]
>> [[200.0, 200.0]]