Please go through the below code and explain me how I am able to achieve the output for the code which I have shared:
class Customer:
pass
c1=Customer()
print(c1)
print(Customer())
print(Customer(),Customer())
print(c1,Customer())
print(Customer())
print(Customer())
Output:
<__main__.Customer object at 0x0172FA90>
<__main__.Customer object at 0x0172FAB0>
<__main__.Customer object at 0x0172FAB0> <__main__.Customer object at 0x0172FB10>
<__main__.Customer object at 0x0172FA90> <__main__.Customer object at 0x0172FAB0>
<__main__.Customer object at 0x0172FAB0>
<__main__.Customer object at 0x0172FAB0>
1 Answer 1
The allocation for the objects just happens to use the same memory location, this isn't something that isn't allowed.
Since you create instances which immediately get collected due to no references existing for them, chances are that Python has the opportunity to re-use the same memory which results in some of them having the same address, see in the documentation for the id()
function:
Return the "identity" of an object. This is an integer which is guaranteed to be unique and constant for this object during its lifetime. Two objects with non-overlapping lifetimes may have the same
id()
value.
(emphasis mine)
Explore related questions
See similar questions with these tags.