Muhamed Huseinbašić Muhamed Huseinbašić - 1 year ago 67
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:
pass

print Point()
print id(Point)


I get this output:

<__main__.Point instance at 0xb71c496c>
3072094252


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.

Demo:

>>> 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
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download