Automatically generating arithmetic operations for a subclass

Sebastian Wiesner basti.wiesner at gmx.net
Tue Apr 14 19:24:56 CEST 2009


<Steven D'Aprano – Dienstag, 14. April 2009 11:09>

> 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?

Metaclasses can be used for this purpuse, see the example for a Roman number 
type [1]

[1] http://paste.pocoo.org/show/97258/

-- 
Freedom is always the freedom of dissenters.
                                      (Rosa Luxemburg)




More information about the Python-list mailing list