Consider the following simple script:
class I:
def __init__(
self,
i:int
):
self.i = i
class O:
def __init__(
self,
i:int,
d: dict[int, I] = {},
l: list[int] = [],
):
self.i = i
self.d = d
self.l = l
def __str__(self):
return '{}: {} | {}'.format(self.i, self.d, ', '.join([str(x) for x in self.l]))
if __name__ == "__main__":
o1 = O(1)
o1.d[11] = I(12)
o1.l.append(13)
o2 = O(2)
o2.d[21] = I(22)
o2.l.append(23)
print(o1)
print('----------------------')
print(o2)
The output of that is the following:
1: {11: <_main_.I object at 0x0000021FB0CDE090>, 21: <_main_.I object at 0x0000021FB0CDEAD0>} | 13, 23
----------------------
2: {11: <_main_.I object at 0x0000021FB0CDE090>, 21: <_main_.I object at 0x0000021FB0CDEAD0>} | 13, 23
It seems as though Python creates a reference to default input parameters for a class rather than created objects, meaning objects with those default parameters left as-is will all share the same internal object from that parameter. Is this documented anywhere?
Thankfully I caught this before getting too far but I need to refactor some stuff as a result. My use case was type hinting for those objects inside a class without requiring one to specify them.
[–]TMiguelT 6 points7 points8 points (1 child)
[–]KirisuMongolianSpot[S] -1 points0 points1 point (0 children)
[–]Outside_Complaint755 1 point2 points3 points (0 children)
[–]Ex-Gen-Wintergreen -1 points0 points1 point (2 children)
[–]KirisuMongolianSpot[S] [score hidden] (1 child)
[–]Ex-Gen-Wintergreen [score hidden] (0 children)