augmented arithmetic operations

Hans Nowak wurmy at earthlink.net
Mon Mar 11 18:01:57 EST 2002


Mike Carifio wrote:
> 
> According to the language ref section "Emulating numeric types"
> (http://www.python.org/doc/current/ref/numeric-types.html),
> I can use special name methods to overload operations. When creating
> "augmented operations"  like __iadd__ (for "+=") is it considered
> "bad form" to create a intermediate value and then assign parts of
> self to the intermediate value? Or is this just an implementation detail?
> 
> 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
> 
> p11 = Point(1,1)
> p22 = Point(2,2)
> p33 = p11 + p22  # p11.__add__(p22)
> p33 += p11  # p33.__iadd__(p1) makes p33 (4,4)
> 
> I'd like to reuse __add__ without having to introduce an intermediate
> object...

This code has a few problems...
1. The constructor's name is __init__, not the name of the class.
2. Indeed, you don't need the intermediate object, since += is
for changing an object in place. So you can do

  self.x = self.x + rhs.x
  self.y = self.y + rhs.y

3. But don't forget

  return self

or the += operator won't work! After " p33 += p11 ", p33 will
be None.

Here's what I would make of the code:

>>> class Point:
	def __init__(self, x, y):
		self.x, self.y = x, y
	def __add__(self, rhs):
		return Point(self.x + rhs.x, self.y + rhs.y)
	def __iadd__(self, rhs):
		self.x = self.x + rhs.x
		self.y = self.y + rhs.y
		return self
	
>>> p11 = Point(1,1)
>>> p22 = Point(2,2)
>>> p33 = p11 + p22
>>> p33.__dict__
{'y': 3, 'x': 3}
>>> p33 += p11
>>> p33.__dict__
{'y': 4, 'x': 4}

HTH,

-- 
Hans (base64.decodestring('d3VybXlAZWFydGhsaW5rLm5ldA==')) 
# decode for email address ;-)
The Pythonic Quarter:: http://www.awaretek.com/nowak/



More information about the Python-list mailing list