Automatically generating arithmetic operations for a subclass

Steven D'Aprano steven at REMOVE.THIS.cybersource.com.au
Tue Apr 14 11:09:56 CEST 2009


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.


My quick-and-dirty count of the __magic__ methods that need to be over-
ridden comes to about 30. That's a fair chunk of unexciting boilerplate.

Is there a trick or Pythonic idiom to make arithmetic operations on a 
class return the same type, without having to manually specify each 
method? I'm using Python 2.5, so anything related to ABCs are not an 
option.

Does anyone have any suggestions?



-- 
Steven



More information about the Python-list mailing list