Reputation: 6087
If the same object is invoked multiple times in python, will the memory location always be the same when I print 'self'?
Upvotes: 5
Views: 1058
Reputation: 67247
Note that, beeing a very high-level language, Python does not define "memory addresses" for objects. Objects do however have an "identity" that can be queried using the built-in id()
function. This identity is guaranteed not to change during an object's lifetime:
Return the “identity” of an object. This is an integer (or long 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.
In CPython, this identity is the underlying memory address, but this is merely an implementation detail; it might be different in other implementations and may even change in future versions of CPython (although this is unlikely).
Upvotes: 4
Reputation: 8481
As mac noticed, memory addresses in Cpython are - by design - static
But even on Cpython you can't relay on this if you are using some c extensions.
Some of them can move objects and manually drive garbage collector.
And if you are using other Python implementations, as PyPy, you are certain not guaranteed that the objects memory location always be the same, and high probably the will move.
Upvotes: 1
Reputation: 43091
AFAIK, memory addresses in Cpython are - by design - static. The memory address of an object can be seen with id()
. The name of the function is a tell-tale of the fact it doesn't change...
See however the comment below, where other SO users pointed out that id()
being the memory address is a detail implementation of Cpython.
HTH!
Upvotes: 6