In Python 2.6 (and earlier) the hex()
and oct()
built-in functions can be overloaded in a class by defining __hex__
and __oct__
You could achieve the same behaviour as for hex and oct by overriding/replacing the built in bin() function with your own implementation that attempted to call bin on the object being passed and fell back to the standard bin() function if the object didn't provide bin. However, on the basis that explicit is better than implicit, coding your application to depend on a custom version of bin() is probably not a good idea so maybe just give the function a different name e.g.
def mybin(n):
try:
return n.__bin__()
except AttributeError:
return bin(n)
As for why the inconsistency in the interface, I'm not sure. Maybe it's because bin() was added more recently so it's a slight oversight?