In Python 2.6 (and earlier) the hex()
and oct()
built-in functions can be overloaded in a class by defining __hex__
and __oct__
special functions. However there is not a __bin__
special function for overloading the behaviour of Python 2.6's new bin()
built-in function.
I want to know if there is any way of flexibly overloading bin()
, and if not I was wondering why the inconsistent interface?
I do know that the __index__
special function can be used, but this isn't flexible as it can only return an integer. My particular use case is from the bitstring module, where leading zero bits are considered significant:
>>> a = BitString(length=12) # Twelve zero bits
>>> hex(a)
'0x000'
>>> oct(a)
'0o0000'
>>> bin(a)
'0b0' <------ I want it to output '0b000000000000'
I suspect that there's no way of achieving this, but I thought it wouldn't hurt to ask!