Search code examples
pythonhexsubclassingrepresentation

subclassing int to attain a Hex representation


Basically I want to have access to all standard python int operators, eg __and__ and __xor__ etc, specifically whenever the result is finally printed I want it represented in Hex format. (Kind of like putting my calculator into Hex mode)

class Hex(int):
  def __repr__(self):
    return "0x%x"%self
  __str__=__repr__ # this certainly helps with printing

if __name__=="__main__":
  print Hex(0x1abe11ed) ^ Hex(440720179)
  print Hex(Hex(0x1abe11ed) ^ Hex(440720179))

Ideally BOTH line of output should be hexadecimal: 0xfacade, however the first one yields decimal: 16435934

Any ideas?


Solution

  • In response to your comment:

    You could write a Mixin by yourself:

    class IntMathMixin:
        def __add__(self, other):
            return type(self)(int(self).__add__(int(other)))
        # ... analog for the others
    

    Then use it like this:

    class Hex(IntMathMixin, int):
        def __repr__(self):
             return "0x%x"%self
        __str__=__repr__