Can bin() be overloaded like oct() and hex() in Python 2.6?

后端 未结 4 460
旧时难觅i
旧时难觅i 2021-02-05 12:26

In Python 2.6 (and earlier) the hex() and oct() built-in functions can be overloaded in a class by defining __hex__ and __oct__

4条回答
  •  后悔当初
    2021-02-05 13:09

    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?

提交回复
热议问题