S
Steven D'Aprano
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?
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?