By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
449,423 Members | 1,294 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 449,423 IT Pros & Developers. It's quick & easy.

Short, crazy example: list-derived class, with __iadd__

P: n/a
class Vec(list):
def __init__(self):
list.__init__(self, [0.0, 0.0])

def __iadd__(self, other):
assert isinstance(other, Vec)
self[0] += other[0]
self[1] += other[1]
print "right now, v is: ", self, " as you'd expect"
v = Vec()
w = Vec()
w[0] = 1.0
w[1] = 2.0
print "v starts:", v

print "(w is:", w, " which is fine)"

v += w

print "(w still is:", w

print "after iadd, v: ", v, " <-- becomes None! What the hey?"
# - running it:

pypython badvec.py
v starts: [0.0, 0.0]
(w is: [1.0, 2.0] which is fine)
right now, v is: [1.0, 2.0]
(w still is: [1.0, 2.0]
later, v is: None <-- becomes None! What the hey?

pypython -V
Python 2.5.1

-- Any explanation from a guru?

Thanks much...
Aug 29 '07 #1
Share this Question
Share on Google+
2 Replies


P: n/a
__iadd__ is supposed to /return/ something, most likely self.

My bad.

On Wed, 29 Aug 2007 20:49:59 +0000, Moon wrote:
class Vec(list):
def __init__(self):
list.__init__(self, [0.0, 0.0])

def __iadd__(self, other):
assert isinstance(other, Vec)
self[0] += other[0]
self[1] += other[1]
print "right now, v is: ", self, " as you'd expect"
v = Vec()
w = Vec()
w[0] = 1.0
w[1] = 2.0
print "v starts:", v

print "(w is:", w, " which is fine)"

v += w

print "(w still is:", w

print "after iadd, v: ", v, " <-- becomes None! What the hey?"
# - running it:

pypython badvec.py
v starts: [0.0, 0.0]
(w is: [1.0, 2.0] which is fine)
right now, v is: [1.0, 2.0]
(w still is: [1.0, 2.0]
later, v is: None <-- becomes None! What the hey?

pypython -V
Python 2.5.1

-- Any explanation from a guru?

Thanks much...
Aug 29 '07 #2

P: n/a
Moon <no***********@zombo.comwrites:
class Vec(list):
def __init__(self):
list.__init__(self, [0.0, 0.0])

def __iadd__(self, other):
assert isinstance(other, Vec)
self[0] += other[0]
self[1] += other[1]
print "right now, v is: ", self, " as you'd expect"
return self
>

v = Vec()
w = Vec()
w[0] = 1.0
w[1] = 2.0
print "v starts:", v

print "(w is:", w, " which is fine)"

v += w

print "(w still is:", w
print "after iadd, v: ", v
>
# - running it:
v starts: [0.0, 0.0]
(w is: [1.0, 2.0] which is fine)
right now, v is: [1.0, 2.0] as you'd expect
(w still is: [1.0, 2.0]
after iadd, v: [1.0, 2.0]

-Marshall

Aug 29 '07 #3

This discussion thread is closed

Replies have been disabled for this discussion.