How do I use the hex () function in Python?

Python Methods and Functions

This function is useful when you want to convert an integer to a prefixed hexadecimal string. Let's see how we could use this function.

 Hex method

The Python hex () function has a very simple syntax:

< script async src = "https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub -6959883099270890" crossorigin = "anonymous"> < ins class = "adsbygoogle" style = "display: inline-block; width: 336px; height: 280px" data-ad-client = "ca-pub-6959883099270890" data-ad-slot = "3943413939">



Using Python hex () on a custom object

We can also use hex () on a custom object. But, if we want to use it successfully, we must define a dunder-method __index __ () for our class.

The hex () method will call __index __ () , so we need it implement. It should return a value, which can be a decimal / binary / octal / hexadecimal number.

 class MyClass: def __init __ (self, value): self .value = value def __index __ (self): print ('__index __ () dunder method called') return self.value my_obj = MyClass (255) print (hex (my_obj)) 

Exit

 __ index __ () dunder method called 0xff 

Indeed, as you can see, it returns what we expected.

First, hex () calls the __index__ method in our custom class.

It then converts the return value to a hexadecimal string (255 - & gt; "0xff").







Get Solution for free from DataCamp guru