augmented arithmetic operations

Quinn Dunkan quinn at upchuck.ugcs.caltech.edu
Tue Mar 12 03:08:59 EST 2002


On Mon, 11 Mar 2002 20:32:57 GMT, Mike Carifio <carifio.nospam at nospam.usys.com>
wrote:
>For example, suppose I introduced Point as a kind of number:
>
>class Point:
>    def Point(self, x, y):
>        self.x = x; self.y = y
>    def __add__(self, rhs):
>        return Point(self.x + rhs.x, self.y + rhs.y)
>    def __iadd__(self, rhs):
>        intermediate = self + rhs  # bad form?
>        self.x = intermediate.x; self.y = intermediate.y

Since you seem to know C++ <wink>, you could do it the usual C++-ly way and
implement __add__ in terms of __iadd__:

   def __add__(self, rhs):
       p = copy.copy(self)
       p += rhs
       return p
   def __iadd__(self, rhs):
       self.x += rhs.x
       self.y += rhs.y



More information about the Python-list mailing list