I'm learning Python (classes at this momment). On this site (on the bottom) first exercise (under 13.7. Exercises) says:
Create and print a Point object, and then use id to print the object's unique identifier. Translate the hexadecimal form into decimal and confirm that they match.
<__main__.Point instance at 0xb71c496c>
Translate the second number into hexadecimal with the
hex() function then test if it is present in the first:
p = Point() hexadecimal_id = hex(id(p)) present = hexadecimal_id in repr(p)
Note that I first store a reference to the
Point() instance; otherwise you'd get a new one with potentially a new
Also, don't confuse the class with the instance; the class is an object in its own right, and as such has a
id() value too.
To go the other way, you'd have to parse out the hexadecimal string; if you are going to assume it is the part after the last space that's doable as:
hexadecimal_id = repr(p).rpartition(' ')[-1][:-1] present = int(hexadecimal_id, 16) == id(p)
str.rpartition() method splits on the last space, and we take whatever comes after it with
[-1] (last element), then shorted that result by one character to remove the
> character at the end.
Once you have the hexadecimal number you can interpret it as an integer with the
int() function, specifying the base as 16.
>>> class Point: ... pass ... >>> p = Point() >>> id(p) 4300021632 >>> hex(id(p)) '0x1004d1f80' >>> p <__main__.Point instance at 0x1004d1f80> >>> hex(id(p)) in repr(p) True >>> # the other direction ... >>> repr(p).rpartition(' ')[-1][:-1] '0x1004d1f80' >>> hexadecimal_id = repr(p).rpartition(' ')[-1][:-1] >>> int(hexadecimal_id, 16) 4300021632 >>> int(hexadecimal_id, 16) == id(p) True