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.

17.12. Exercises 167object-oriented programming: Astyleofprogramminginwhichdataandtheoperationsthatmanipulateitareorganized intoclasses and methods.method: Afunctionthatisdefinedinsideaclassdefinitionandisinvokedoninstancesofthatclass.subject: The object amethod isinvoked on.operator overloading: Changingthebehaviorofanoperatorlike+soitworkswithauser-definedtype.type-based dispatch: A programming pattern that checks the type of an operand and invokes differentfunctions for different types.polymorphic: Pertaining toafunction that can work withmorethan one type.17.12 ExercisesExercise17.6 Thisexerciseisacautionarytaleaboutoneofthemostcommon,anddifficulttofind,errorsin<strong>Python</strong>.1. Writeadefinition foraclass namedKangaroowiththefollowing methods:(a) An __init__ method that initializes an attribute named pouch_contents to an emptylist.(b) A method named put_in_pouch that takes an object of any type and adds it topouch_contents.(c) A __str__ method that returns a string representation of the Kangaroo object and thecontents of thepouch.Test your code by creating two Kangaroo objects, assigning them to variables named kangaandroo,and then addingrootothecontents ofkanga’spouch.2. Downloadthinkpython.com/code/BadKangaroo.py. Itcontainsasolutiontothepreviousproblem withone big, nastybug. Findand fixthe bug.If you get stuck, you can download thinkpython.com/code/GoodKangaroo.py, which explainstheproblem and demonstrates asolution.Exercise 17.7 Visual is a <strong>Python</strong> module that provides 3-D graphics. It is not always included in a<strong>Python</strong>installation,soyoumighthavetoinstallitfromyoursoftwarerepositoryor,ifit’snotthere,fromvpython.org.The following example creates a 3-D space that is 256 units wide, long and high, and sets the“center” tobe thepoint (128,128,128). Then itdraws a bluesphere.from visual import *scene.range = (256, 256, 256)scene.center = (128, 128, 128)color = (0.1, 0.1, 0.9) # mostly bluesphere(pos=scene.center, radius=128, color=color)

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

Saved successfully!

Ooh no, something went wrong!