Mari0 Mari0 - 2 months ago 12
Python Question

Different class instances use same memory location

I was playing around with the

library, when I noticed that sometimes, different class instances are at the same memory location.

Both of the below examples are showcasing said behaviour:

class DemoClass:
def __init__(self): = 'demoName'

#example 1
for i in range(3):
print (DemoClass())

#example 2
[print(DemoClass()) for i in range(3)]

#Output for both example 1 and example 2
#Note that the memory locations are identical in the output
<__main__.DemoClass object at 0x00CEE610>
<__main__.DemoClass object at 0x00CEE610>
<__main__.DemoClass object at 0x00CEE610>

This was quite startling to me, so maybe you could explain why this occurs.

The way in which the program acts as I would expect it to is as follows.

demo = [DemoClass() for i in range(3)]
for i in demo:
print (i)

<__main__.DemoClass object at 0x01F7E630>
<__main__.DemoClass object at 0x01F7ED30>
<__main__.DemoClass object at 0x01F7E670>


In your first 2 examples, once the call to print has finished, the object no longer has a reference, and so can be re-used the next time that type of object is created.

In the second, all of the instances have references at the same time, and thus must be distinct.

I wouldn't rely on this behavior, though: for example, there might be other unreferenced instances of that object lying about.