12.07.2015 Views

Think Python - Denison University

Think Python - Denison University

Think Python - Denison University

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

15.6. Copying 149>>> print box.width100.0>>> print box.height200.0>>> grow_rectangle(box, 50, 100)>>> print box.width150.0>>> print box.height300.0Insidethe function,rectisan alias forbox,soifthe function modifiesrect,boxchanges.Exercise 15.2 Write a function named move_rectangle that takes a Rectangle and two numbersnameddxanddy. Itshouldchangethelocationoftherectanglebyaddingdxtothexcoordinateofcornerand addingdytotheycoordinate ofcorner.15.6 CopyingAliasing can make a program difficult to read because changes in one place might have unexpectedeffectsinanotherplace. Itishardtokeeptrackofallthevariablesthatmightrefertoagivenobject.Copying an object is often an alternative to aliasing. The copy module contains a function calledcopythat can duplicate any object:>>> p1 = Point()>>> p1.x = 3.0>>> p1.y = 4.0>>> import copy>>> p2 = copy.copy(p1)p1andp2contain the samedata, but they arenot the samePoint.>>> print_point(p1)(3.0, 4.0)>>> print_point(p2)(3.0, 4.0)>>> p1 is p2False>>> p1 == p2FalseThe is operator indicates that p1 and p2 are not the same object, which is what we expected. Butyou might have expected == to yield True because these points contain the same data. In that case,you will be disappointed to learn that for instances, the default behavior of the == operator is thesame as the is operator; it checks object identity, not object equivalence. This behavior can bechanged—we’ll seehow later.If you use copy.copy to duplicate a Rectangle, you will find that it copies the Rectangle object butnot the embedded Point.

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!