Automatically generating arithmetic operations for a subclass

Gerard Flanagan grflanagan at
Tue Apr 14 13:36:57 CEST 2009

Steven D'Aprano wrote:
> I have a subclass of int where I want all the standard arithmetic 
> operators to return my subclass, but with no other differences:
> class MyInt(int):
>     def __add__(self, other):
>         return self.__class__(super(MyInt, self).__add__(other))
>     # and so on for __mul__, __sub__, etc.

Just an idea:

def myint(meth):
     def mymeth(*args):
         return MyInt(meth(*args))
     return mymeth

class MyIntMeta(type):

     method_names = 'add sub mul neg'.split()

     def __new__(cls, name, bases, attrs):
         t = type.__new__(cls, name, bases, attrs)
         for name in MyIntMeta.method_names:
             name = '__%s__' % name
             meth = getattr(t, name)
             setattr(t, name, myint(meth))
         return t

class MyInt(int):
     __metaclass__ = MyIntMeta

a = MyInt(3)
b = MyInt(3000)

print a
print b
c = a + b
print c
assert isinstance(c, MyInt)
d = c * MyInt(4)
print d
e = c * 6 * a * b
print e
assert isinstance(e, MyInt)

x = -e
print x
assert isinstance(x, MyInt)

More information about the Python-list mailing list