Muhamed Huseinbašić Muhamed Huseinbašić - 4 years ago 128
Python Question

Object's unique identifier (translate from hexadecimal into decimal)

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.

I need help with this because I'm not quite sure I understand what I have to do.

If I do:

class Point:

print Point()
print id(Point)

I get this output:

<__main__.Point instance at 0xb71c496c>

So, should I do this first part of exercise like this or? And what now? I assume that this second line is decimal number (Am I right?). But what with the first line? How to translate it into decimal?

Answer Source

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 id() value.

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)

Here, the 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)
>>> hex(id(p))
>>> p
<__main__.Point instance at 0x1004d1f80>
>>> hex(id(p)) in repr(p)
>>> # the other direction
>>> repr(p).rpartition(' ')[-1][:-1]
>>> hexadecimal_id = repr(p).rpartition(' ')[-1][:-1]
>>> int(hexadecimal_id, 16)
>>> int(hexadecimal_id, 16) == id(p)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download