In this post, we will see about Python hex() function.
Python hex() method converts an int to hexadecimal with ‘0x’ as prefix.If x is not an Python int then it needs to define __index__ method which returns an int.
x is the int which you want to convert to hexadecimal.
It returns hexadecimal representation of int.
Let’s understand with help of simple example:
print('Hexadecimal representation of 9:',hex(9)) print('Hexadecimal representation of 13:',hex(13)) print('Hexadecimal representation of 101:',hex(101))
Hexadecimal representation of 13: 0xd
Hexadecimal representation of 101: 0x65
hex() for user defined class
You need to implement __index__() method which returns an int in case of user defined class.We are simply returning 30 from below __index__() and when you call hex(country), it internally executes __index__() of country class only.
class Country: name = 'India' population = 10000 def __index__(self): return 30 country = Country() print(hex(country))
That’s all about hex() function in Python.