augmented arithmetic operations
Mike Carifio
carifio.nospam at nospam.usys.com
Mon Mar 11 15:32:57 EST 2002
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...
More information about the Python-list
mailing list