[Tutor] Why does the Hex builtin function in Python return a string ?

John Fouhy john at fouhy.net
Tue Aug 26 03:27:14 CEST 2008


2008/8/26 John Fouhy <john at fouhy.net>:
> The hex() function (and oct() too) provides you with a different
> string representation from the default.  If you want to change python
> to display integers in hex instead of decimal by default, I can't help
> you.. (well, maybe you could subclass int, and change __repr__ and
> __str__ to return hex strings)

Actually, that was easier than I thought:

class HexInt(int):
    def __repr__(self):
        return hex(self)
    def __str__(self):
        return str(self)
    def __add__(self, other):
        return HexInt(int(self)+int(other))
    def __sub__(self, other):
        return HexInt(int(self)-int(other))
    def __mul__(self, other):
        return HexInt(int(self)*int(other))
    def __div__(self, other):
        return HexInt(int(self)/int(other))

>>> h1 = HexInt(13)
>>> h2 = HexInt(21)
>>> h1, h2
(0xd, 0x15)
>>> h1+h2
0x22
>>> h1-h2
-0x8
>>> h1*h2
0x111
>>> int(h1*h2)
273
>>> h1+16
0x1d

Of course, there's obvious problems if you want to mix this with
floats :-/  And I'm not sure what you'd gain, since as mentioned,
integers are integers, whatever they look like.

-- 
John.


More information about the Tutor mailing list