[Tutor] confusion about cloning (graphics)
David
ldl08 at gmx.net
Sun Feb 1 09:34:10 CET 2009
Hello list,
I continue my reading of Harrington. In section 2.4. he is making a
point about the need to clone, as otherwise the object associated to
parameter corner (the point (20, 50)) takes the same value as corner2.
That is: corner2 changes corner, which in turn changes the point (20,
50). Here is the faulty code Harrington provides:
<code>
'''Program: makeRectBad.py
Attempt a function makeRect (incorrectly),
which takes a takes a corner point and dimensions to construct a Rectangle.
'''
from graphics import * # based on Zelle's graphics.py module
def makeRect(corner, width, height): # Incorrect!
'''Return a new Rectangle given one corner Point and the dimensions.'''
corner2 = corner
corner2.move(width, height)
return Rectangle(corner, corner2)
def main():
winWidth = 300
winHeight = 300
win = GraphWin('Draw a Rectangle (NOT!)', winWidth, winHeight)
win.setCoords(0, 0, winWidth, winHeight)
rect = makeRect(Point(20, 50), 250, 200)
rect.draw(win)
# Wait for another click to exit
msg = Text(Point(winWidth/2, 20),'Click anywhere to quit.')
msg.draw(win)
win.getMouse()
win.close()
main()
</code>
This behaviour stuns me, because I was always following the belief that
when variable2 refers to another variable1, the value of variable1 would
NOT change, even as I operate on variable2 - just like my little
experiment at the promt:
In [10]: x = 5
In [11]: y = x
In [12]: y + 2
Out[12]: 7
In [13]: x
Out[13]: 5
So here is my question: what have I failed to grasp? Are those different
issues? If so, why?
I'd appreciate it if you could give me a short comment, this one bothers
me ;-)
David
More information about the Tutor
mailing list