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.

32 Chapter 4. Case study: interface design4.4 EncapsulationThe first exercise asks you to put your square-drawing code into a function definition and then callthefunction, passing theturtleas aparameter. Here isasolution:def square(t):for i in range(4):fd(t, 100)lt(t)square(bob)The innermost statements, fd and lt are indented twice to show that they are inside the for loop,whichisinsidethefunctiondefinition. Thenextline,square(bob),isflushwiththeleftmargin,sothat isthe end of both theforloop and the function definition.Insidethefunction,treferstothesameturtlebobrefersto,solt(t)hasthesameeffectaslt(bob).So why not call the parameter bob? The idea is that t can be any turtle, not just bob, so you couldcreate asecond turtleand pass itas anargument tosquare:ray = Turtle()square(ray)Wrapping a piece of code up in a function is called encapsulation. One of the benefits of encapsulationis that it attaches a name to the code, which serves as a kind of documentation. Anotheradvantage is that if you re-use the code, it is more concise to call a function twice than to copy andpaste thebody!4.5 GeneralizationThe next stepistoadd alengthparameter tosquare. Here isasolution:def square(t, length):for i in range(4):fd(t, length)lt(t)square(bob, 100)Adding a parameter to a function is called generalization because it makes the function more general:inthe previous version, thesquare isalways thesame size;inthis version itcan be any size.The next step is also a generalization. Instead of drawing squares,polygondraws regular polygonswithany number of sides. Hereisasolution:def polygon(t, n, length):angle = 360.0 / nfor i in range(n):fd(t, length)lt(t, angle)polygon(bob, 7, 70)

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

Saved successfully!

Ooh no, something went wrong!