I'm trying to create a user defined class for a 'Track' object, which is just a line with two ends ('Side' s). These 2 sides are of type of another user defined class; their instances in 'track' are named 'a' and 'b', and are created in track's constructor. The 'Side' class has a member of class 'Coord', which itself has the x- and y-coordinates as members (as float). Now, if I give the constructor of the 'Side' class a default value for the coordinates, like so:
class Side(object):
def __init__(self, co=Coord(0, 0)):
self.coords = co
subsequently my 'a' and 'b' Side-objects will be shallow copies (?). This means if I assign e.g. 20 to E1.a.coords.x, this value will be also 20 in E2.a.coords.x. Looking at the debugger, I can see that the 'Coord' instance named 'coords', in all its usages (in E1.a, E2.b, ...) actually have the same address.
However, when I take this initialization away from class 'Coord' and instead apply it to the caller (class Track), as in a = Side(Coord(10, 20)), everything is fine.
Being sort of a newbie to Python (less than 6 mo. exp.), I of course wonder how this is happening, and what's going on under the hood here. Maybe someone can be so nice as to explain, thanks! Below is the whole minimum working example:
class Coord(object):
def __init__(self, x, y):
self.x = x
self.y = y
class Side(object):
def __init__(self, co=Coord(0, 0)):
self.coords = co
class Track(object):
def __init__(self):
self.a = Side()
self.b = Side()
E1 = Track()
E1.a.coords.x = 10
print(E1.a.coords.x) # 10, as expected
E2 = Track()
E2.a.coords.x = 20
print(E2.a.coords.x) # 20, as expected
print(E1.a.coords.x) # should be 10, is 20 though
Output:
10
20
20
Thanks in advance, Bernd
Python 3.10.2, PyCharm Community Ed. 2021.3.2 @Win11 (21H2)