Aug-19-2019, 07:02 PM
Alright, so let me restructure your question, to make sure I understand it right.
Given this code:
The loc variable is created with copies of the x/y variables, not references to them. So changes to the x/y variables will not effect the loc.
The easy way to fix this, is to use a method to return the current location:
Given this code:
class Room: def __init__(self, x, y): self.x = x self.y = y self.loc = (x, y) room_1 = Room(0, 0) print(room_1.loc) room_1.y += 1 print(room_1.loc)...why is the same tuple printed twice? Or, why didn't the change to the
y
variable also change the loc
variable?The loc variable is created with copies of the x/y variables, not references to them. So changes to the x/y variables will not effect the loc.
The easy way to fix this, is to use a method to return the current location:
def get_loc(self): return (self.x, self.y)The other option would be to use objects to store positioning, instead of primitive types (like an int). That would look something like this:
class Point: def __init__(self, x, y): self.x = x self.y = y def get_loc(self): return (self.x, self.y) def __str__(self): return "Point: ({0}, {1})".format(self.x, self.y) class Room: def __init__(self, x, y): self.loc = Point(x, y) room_1 = Room(0, 0) print(room_1.loc) room_1.loc.y += 1 print(room_1.loc)