When python gives me the location of an object in memory, what is that for, other than distinguishing between instances in the interactive prompt?
Example:
>>>inspect.walktree
<function walktree at 0x2a97410>
This is the default string representation that is returned if you call repr(obj)
on an object which doesn't define the magic __repr__
method (or didn't override the default implementation inherited from object
, in the case of new-style objects).
That default string has the purpose of giving the programmer useful information about the type and identity of the underlying object.
Internally, the id
function is called to get the number included in the string:
>>> o = object()
>>> o
<object object at 0x7fafd75d10a0>
>>> id(o)
140393209204896
>>> "%x" % id(o)
'7fafd75d10a0'
Note that id
does NOT represent a unique ID. It can happen that during the lifetime of a program several objects will have the same ID (although never at the the same time).
It also does not have to correlate with the location of the object in memory (although it does in CPython).
You can easily override the representation string for your own classes, by the way:
class MyClass(object):
def __repr__(self):
return "meaningful representation (or is it?)"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With