pythonobject

Creating my own "integer" object in Python


Essentially I want to be able to do something like:

a = Integer(1)
a += 1
print a

And of course printing the number two as result. What methods do I need to create to get this behaviour in my Integer class?

Disclaimer: I'm not planning to use this for "real", just curious.


Solution

  • This is a simple and incomplete example. Look at methods __sub__, __div__ and so on.

    class Integer(object):
        def __init__(self, val=0):
            self._val = int(val)
        def __add__(self, val):
            if isinstance(val, Integer):
                return Integer(self._val + val._val)
            return self._val + val
        def __iadd__(self, val):
            self._val += val
            return self
        def __str__(self):
            return str(self._val)
        def __repr__(self):
            return 'Integer(%s)' % self._val
    

    Then

    n = Integer()
    print n
    m = Integer(7)
    m+=5
    print m
    

    EDIT fixed __repr__ and added __iadd__. Thanks to @Keith for pointing problems out. EDIT Fixed __add__ to allow addition between Integers.