12.07.2015 Views

Think Python - Denison University

Think Python - Denison University

Think Python - Denison University

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

150 Chapter 15. Classesand objects>>> box2 = copy.copy(box)>>> box2 is boxFalse>>> box2.corner is box.cornerTrueHere iswhat the object diagram looks like:boxwidth100.0100.0widthbox2heightcorner200.0xy0.00.0200.0heightcornerThis operation is called a shallow copy because it copies the object and any references it contains,but not theembedded objects.Formostapplications,thisisnotwhatyouwant. Inthisexample,invokinggrow_rectangleononeof the Rectangles would not affect the other, but invoking move_rectangle on either would affectboth! This behavior isconfusing and error-prone.Fortunately, the copy module contains a method named deepcopy that copies not only the objectbut also the objects it refers to, and the objects they refer to, and so on. You will not be surprised tolearn that thisoperation iscalled adeep copy.>>> box3 = copy.deepcopy(box)>>> box3 is boxFalse>>> box3.corner is box.cornerFalsebox3andboxare completely separate objects.Exercise15.3 Writeaversionofmove_rectanglethatcreatesandreturnsanewRectangleinsteadof modifying the oldone.15.7 DebuggingWhen you start working with objects, you are likely to encounter some new exceptions. If you trytoaccess an attributethat doesn’t exist, you get anAttributeError:>>> p = Point()>>> print p.zAttributeError: Point instance has no attribute 'z'Ifyou arenot surewhat type an object is,you can ask:>>> type(p)If you are not sure whether an object has a particular attribute, you can use the built-in functionhasattr:

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

Saved successfully!

Ooh no, something went wrong!