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