← 学习库 Think Python 2e 目录

Chapter 5

> 来源: Think Python 2e (Allen B. Downey)

> 原页: https://greenteapress.com/thinkpython/html/thinkpython005.html

\

[插图缺失:thinkpython004.html]
[ [](thinkpython006.html)

------------------------------------------------------------------------

Chapter 4   Case study: interface design

Code examples from this chapter are available from http://thinkpython.com/code/polygon.py.

4.1   TurtleWorld

To accompany this book, I have written a package called Swampy. You can download Swampy from http://thinkpython.com/swampy; follow the instructions there to install Swampy on your system.

A package is a collection of modules; one of the modules in Swampy is TurtleWorld, which provides a set of functions for drawing lines by steering turtles around the screen.

If Swampy is installed as a package on your system, you can import TurtleWorld like this:

from swampy.TurtleWorld import *

If you downloaded the Swampy modules but did not install them as a package, you can either work in the directory that contains the Swampy files, or add that directory to Python’s search path. Then you can import TurtleWorld like this:

from TurtleWorld import *

The details of the installation process and setting Python’s search path depend on your system, so rather than include those details here, I will try to maintain current information for several systems at http://thinkpython.com/swampy

Create a file named mypolygon.py and type in the following code:

from swampy.TurtleWorld import *

world = TurtleWorld()

bob = Turtle()

print bob

wait_for_user()

The first line imports everything from the TurtleWorld module in the swampy package.

The next lines create a TurtleWorld assigned to world and a Turtle assigned to bob. Printing bob yields something like:

swampy020

This means that bob refers to an instance of a Turtle as defined in module swampy022. In this context, “instance” means a member of a set; this Turtle is one of the set of possible Turtles.

swampy023 tells TurtleWorld to wait for the user to do something, although in this case there’s not much for the user to do except close the window.

TurtleWorld provides several turtle-steering functions: fd and fd for forward and backward, and fd and fd for left and right turns. Also, each Turtle is holding a pen, which is either down or up; if the pen is down, the Turtle leaves a trail when it moves. The functions fd and fd stand for “pen up” and “pen down.”

To draw a right angle, add these lines to the program (after creating bob and before calling swampy031):

swampy032

The first line tells bob to take 100 steps forward. The second line tells him to turn left.

When you run this program, you should see bob move east and then north, leaving two line segments behind.

Now modify the program to draw a square. Don’t go on until you’ve got it working!

4.2   Simple repetition

Chances are you wrote something like this (leaving out the code that creates TurtleWorld and waits for the user):

swampy035

We can do the same thing more concisely with a bob statement. Add this example to swampy037 and run it again:

swampy038

You should see something like this:

swampy039

This is the simplest use of the bob statement; we will see more later. But that should be enough to let you rewrite your square-drawing program. Don’t go on until you do.

Here is a bob statement that draws a square:

swampy042

The syntax of a bob statement is similar to a function definition. It has a header that ends with a colon and an indented body. The body can contain any number of statements.

A bob statement is sometimes called a loop because the flow of execution runs through the body and then loops back to the top. In this case, it runs the body four times.

This version is actually a little different from the previous square-drawing code because it makes another turn after drawing the last side of the square. The extra turn takes a little more time, but it simplifies the code if we do the same thing every time through the loop. This version also has the effect of leaving the turtle back in the starting position, facing in the starting direction.

4.3   Exercises

The following is a series of exercises using TurtleWorld. They are meant to be fun, but they have a point, too. While you are working on them, think about what the point is.

The following sections have solutions to the exercises, so don’t look until you have finished (or at least tried).

  1. Write a function called swampy that takes a parameter named t, which is a turtle. It should use the turtle to draw a square.

    Write a function call that passes bob as an argument to swampy, and then run the program again.

  2. Add another parameter, named swampy, to swampy. Modify the body so length of the sides is swampy, and then modify the function call to provide a second argument. Run the program again. Test your program with a range of values for swampy.
  3. The functions fd and fd make 90-degree turns by default, but you can provide a second argument that specifies the number of degrees. For example, swampy055 turns bob 45 degrees to the left.

    Make a copy of swampy and change the name to swampy0. Add another parameter named t and modify the body so it draws an n-sided regular polygon. Hint: The exterior angles of an n-sided regular polygon are 360/n degrees.

  4. Write a function called swampy that takes a turtle, t, and radius, t, as parameters and that draws an approximate circle by invoking swampy0 with an appropriate length and number of sides. Test your function with a range of values of t.

    Hint: figure out the circumference of the circle and make sure that swampy065.

    Another hint: if bob is too slow for you, you can speed him up by changing swampy067, which is the time between moves, in seconds. swampy068 ought to get him moving.

  5. Make a more general version of swampy called bob that takes an additional parameter world, which determines what fraction of a circle to draw. world is in units of degrees, so when swampy073, bob should draw a complete circle.

4.4   Encapsulation

The first exercise asks you to put your square-drawing code into a function definition and then call the function, passing the turtle as a parameter. Here is a solution:

swampy075

The innermost statements, fd and fd are indented twice to show that they are inside the bob loop, which is inside the function definition. The next line, swampy079, is flush with the left margin, so that is the end of both the bob loop and the function definition.

Inside the function, t refers to the same turtle bob refers to, so world has the same effect as swampy0. So why not call the parameter bob? The idea is that t can be any turtle, not just bob, so you could create a second turtle and pass it as an argument to swampy:

swampy089

Wrapping a piece of code up in a function is called encapsulation. One of the benefits of encapsulation is that it attaches a name to the code, which serves as a kind of documentation. Another advantage is that if you re-use the code, it is more concise to call a function twice than to copy and paste the body!

4.5   Generalization

The next step is to add a swampy parameter to swampy. Here is a solution:

swampy092

Adding a parameter to a function is called generalization because it makes the function more general: in the previous version, the square is always the same size; in this version it can be any size.

The next step is also a generalization. Instead of drawing squares, swampy0 draws regular polygons with any number of sides. Here is a solution :rule

swampy094

This draws a 7-sided polygon with side length 70. If you have more than a few numeric arguments, it is easy to forget what they are, or what order they should be in. It is legal, and sometimes helpful, to include the names of the parameters in the argument list:

swampy095

These are called keyword arguments because they include the parameter names as “keywords” (not to be confused with Python keywords like world and bob).

This syntax makes the program more readable. It is also a reminder about how arguments and parameters work: when you call a function, the arguments are assigned to the parameters.

4.6   Interface design

The next step is to write swampy, which takes a radius, t, as a parameter. Here is a simple solution that uses swampy1 to draw a 50-sided polygon:

swampy101

The first line computes the circumference of a circle with radius t using the formula 2 π r. Since we use swampy1, we have to import bob0. By convention, swampy statements are usually at the beginning of the script.

t is the number of line segments in our approximation of a circle, so swampy is the length of each segment. Thus, swampy1 draws a 50-sides polygon that approximates a circle with radius t.

One limitation of this solution is that t is a constant, which means that for very big circles, the line segments are too long, and for small circles, we waste time drawing very small segments. One solution would be to generalize the function by taking t as a parameter. This would give the user (whoever calls swampy) more control, but the interface would be less clean.

The interface of a function is a summary of how it is used: what are the parameters? What does the function do? And what is the return value? An interface is “clean” if it is “as simple as possible, but not simpler. (Einstein)”

In this example, t belongs in the interface because it specifies the circle to be drawn. t is less appropriate because it pertains to the details of how the circle should be rendered.

Rather than clutter up the interface, it is better to choose an appropriate value of t depending on swampy116:

swampy117

Now the number of segments is (approximately) swampy118, so the length of each segment is (approximately) 3, which is small enough that the circles look good, but big enough to be efficient, and appropriate for any size circle.

4.7   Refactoring

When I wrote swampy, I was able to re-use swampy1 because a many-sided polygon is a good approximation of a circle. But bob is not as cooperative; we can’t use swampy1 or swampy to draw an arc.

One alternative is to start with a copy of swampy1 and transform it into bob. The result might look like this:

swampy126

The second half of this function looks like swampy1, but we can’t re-use swampy1 without changing the interface. We could generalize swampy1 to take an angle as a third argument, but then swampy1 would no longer be an appropriate name! Instead, let’s call the more general function swampy13:

swampy132

Now we can rewrite swampy1 and bob to use swampy13:

swampy136

Finally, we can rewrite swampy to use bob:

swampy139

This process—rearranging a program to improve function interfaces and facilitate code re-use—is called refactoring. In this case, we noticed that there was similar code in bob and swampy1, so we “factored it out” into swampy14.

If we had planned ahead, we might have written swampy14 first and avoided refactoring, but often you don’t know enough at the beginning of a project to design all the interfaces. Once you start coding, you understand the problem better. Sometimes refactoring is a sign that you have learned something.

4.8   A development plan

A development plan is a process for writing programs. The process we used in this case study is “encapsulation and generalization.” The steps of this process are:

  1. Start by writing a small program with no function definitions.
  2. Once you get the program working, encapsulate it in a function and give it a name.
  3. Generalize the function by adding appropriate parameters.
  4. Repeat steps 1–3 until you have a set of working functions. Copy and paste working code to avoid retyping (and re-debugging).
  5. Look for opportunities to improve the program by refactoring. For example, if you have similar code in several places, consider factoring it into an appropriately general function.

This process has some drawbacks—we will see alternatives later—but it can be useful if you don’t know ahead of time how to divide the program into functions. This approach lets you design as you go along.

4.9   docstring

A docstring is a string at the beginning of a function that explains the interface (“doc” is short for “documentation”). Here is an example:

swampy144

This docstring is a triple-quoted string, also known as a multiline string because the triple quotes allow the string to span more than one line.

It is terse, but it contains the essential information someone would need to use this function. It explains concisely what the function does (without getting into the details of how it does it). It explains what effect each parameter has on the behavior of the function and what type each parameter should be (if it is not obvious).

Writing this kind of documentation is an important part of interface design. A well-designed interface should be simple to explain; if you are having a hard time explaining one of your functions, that might be a sign that the interface could be improved.

4.10   Debugging

An interface is like a contract between a function and a caller. The caller agrees to provide certain parameters and the function agrees to do certain work.

For example, swampy14 requires four arguments: t has to be a Turtle; t is the number of line segments, so it has to be an integer; swampy should be a positive number; and world has to be a number, which is understood to be in degrees.

These requirements are called preconditions because they are supposed to be true before the function starts executing. Conversely, conditions at the end of the function are postconditions. Postconditions include the intended effect of the function (like drawing line segments) and any side effects (like moving the Turtle or making other changes in the World).

Preconditions are the responsibility of the caller. If the caller violates a (properly documented!) precondition and the function doesn’t work correctly, the bug is in the caller, not the function.

4.11   Glossary

instance:

A member of a set. The TurtleWorld in this chapter is a member of the set of TurtleWorlds.

loop:

A part of a program that can execute repeatedly.

encapsulation:

The process of transforming a sequence of statements into a function definition.

generalization:

The process of replacing something unnecessarily specific (like a number) with something appropriately general (like a variable or parameter).

keyword argument:

An argument that includes the name of the parameter as a “keyword.”

interface:

A description of how to use a function, including the name and descriptions of the arguments and return value.

refactoring:

The process of modifying a working program to improve function interfaces and other qualities of the code.

development plan:

A process for writing programs.

docstring:

A string that appears in a function definition to document the function’s interface.

precondition:

A requirement that should be satisfied by the caller before a function starts.

postcondition:

A requirement that should be satisfied by the function before it ends.

4.12   Exercises

Exercise 1  

Download the code in this chapter from swampy150.

  1. Write appropriate docstrings for swampy1, bob and swampy.
  2. Draw a stack diagram that shows the state of the program while executing swampy154. You can do the arithmetic by hand or add world statements to the code.
  3. The version of bob in Section 4.7 is not very accurate because the linear approximation of the circle is always outside the true circle. As a result, the turtle ends up a few units away from the correct destination. My solution shows a way to reduce the effect of this error. Read the code and see if it makes sense to you. If you draw a diagram, you might see how it works.


[插图缺失:thinkpython005.png]

Figure 4.1: Turtle flowers.


Exercise 2  

Write an appropriately general set of functions that can draw flowers as in Figure 4.1.

Solution: swampy157, also requires swampy158.


[插图缺失:thinkpython006.png]

Figure 4.2: Turtle pies.


Exercise 3  

Write an appropriately general set of functions that can draw shapes as in Figure 4.2.

Solution: swampy159.

Exercise 4  

The letters of the alphabet can be constructed from a moderate number of basic elements, like vertical and horizontal lines and a few curves. Design a font that can be drawn with a minimal number of basic elements and then write functions that draw letters of the alphabet.

You should write one function for each letter, with names swampy, swampy, etc., and put your functions in a file named swampy162. You can download a “turtle typewriter” from swampy163 to help you test your code.

Solution: swampy164, also requires swampy165.

Exercise 5  

Read about spirals at swampy166; then write a program that draws an Archimedian spiral (or one of the other kinds). Solution: swampy167.

Contribute

If you would like to make a contribution to support my books, you can use the button below. Thank you!

Pay what you want:

Small $1.00 USD Medium $5.00 USD Large $10.00 USD X-Large $20.00 USD XX-Large $50.00 USD

Are you using one of our books in a class?

We'd like to know about it. Please consider filling out this short survey.


------------------------------------------------------------------------

\

[插图缺失:thinkpython004.html]
[ [](thinkpython006.html)

---

← Chapter 4Chapter 6 →