Log in / Register
Home arrow Computer Science arrow Python Programming Fundamentals
< Prev   CONTENTS   Next >

4 Using Objects

In this chapter we explore objects and code re-use. Python is an object-oriented language and learning to use objects can make programming fun and productive. In this chapter we'll explore object-oriented programming by using the turtle module. If we had to write every program from scratch, we wouldn't be able to get very much done. Part of the fun of programming is using something someone else has written to solve a problem quickly. Another fun aspect of programming is writing code that others may want to use in their programs. In fact, programmers sometimes become famous among their peers by writing code that turns out to be very valuable: people like Yukihiro Matsumoto [2], who created the Ruby programming language, or Robin Milner [6] who described the type inference system used by Standard ML, or Guido van Rossum the creator of the Python Programming Language [10]. There

are many, many computer scientists that could be named here.

Python makes it easy for programmers who want to share code with others to do just that. A module is a file containing Python code. When a programmer needs to use code another programmer wrote, he or she can import the module containing the code they want to use into their program. Modules can be imported into other modules so one programmer can easily use code that another programmer wrote. One such module is called turtle. The turtle module includes code that helps us draw figures in the sand. A turtle can walk around a beach dragging his or her tail in the sand or raising that tail. When the tail is down, the turtle leaves a track. When the tail is up the turtle leaves no trail. With this simple analogy we can draw some pretty interesting pictures. The idea has been around since at least the late 1960s when Seymour Papert added turtle graphics to the Logo programming language [4]. Gregor Lingl, an Austrian high school teacher, has implemented a version of turtle graphics for Python that now is part of the Python programming environment.

To use a module it needs to be imported into your program. There are two ways to import a module. The decision of which to use is partly based on convenience and partly based on safety of your program. The safe way to import a module is to write import module where is the name of a module. The module must be in the current directory or in one of the directories where your installation of Python knows to look. When importing a module in this way you must prefix any use of code within the module with the module name. If you want to call a function or use a type, t, that is defined in the imported module, you must write module.t. This is safe because there will never be the possibility of using the same name within two different modules since all names must be qualified with the module name. Using qualified names makes importing safe, but is not the most convenient when writing code.

Example 4.1 Here is a program that imports the turtle code and uses it to draw a square.

1 i m p o r t turtle


3 t = turtle.Turtle ()

4 screen = t.getscreen ()

5 t.forward (25)

6 t.left (90)

7 t.forward (25)

8 t.left (90)

9 t.forward (25)

10 t.left (90)

11 t.forward (25)

12 screen.exitonclick ()

If you are going to try this code, DO NOT call it If you name your own program the same as a module name, then Python will no longer import the correct module. If you already did this you must delete the turtle.pyc file in your folder and rename your module to something other than

Example 4.1 imports the turtle module using import turtle. Once the module is imported, a Turtle object can be created. In this case, the programmer must write turtle.Turtle() to create an object of type Turtle. Because the Turtle type or class resides in the turtle module the fully qualified name of turtle.Turtle() must be written to create a Turtle object. Figure 4.1 shows the turtle reference pointing to a Turtle object just like integer variables are references that point to int objects and string variables are references that point to str objects. Initializing a Turtle object and making a reference point to it is just like creating any other object in Python.

Fig. 4.1 A turtle object

Practice 4.1 Write some code that uses a for loop to draw a square using the turtle module.

A more convenient way to import a module is to write from module import *. In this case we could import the turtle module by writing from turtle import *. This imports the turtle module as before but merges all the names of functions, types, and classes in the turtle module with the names of functions, variables, and types in your program.

Example 4.2 Here is a program that draws a pentagon using the other form of import.

1 from turtle i m p o r t *


3 t = Turtle ()

4 screen = t.getscreen ()

5 t.forward (25)

6 t.left (72.5)

7 t.forward (25)

8 t.left (72.5)

9 t.forward (25)

10 t.left (72.5)

11 t.forward (25)

12 t.left (72.5)

13 t.forward (25)

14 screen.exitonclick ()

Example 4.2 imports by merging the namespace of the turtle module and the program in the example. Both Examples 4.1 and 4.2 demonstrate how to call a method on an object. This means that any variables defined in the turtle module will be overridden if they are also defined in the code in Example 4.2. For example, we would want to be careful and not name something Turtle in our code since that would mean that we would no longer be able to create a Turtle object in our program. Redefining a name like this is not permanent though. The problem only exists within the program. Once the program terminates, the next time we import the turtle module, the Turtle class would be available again.

Not every class must be imported from a module. Python already makes the int, float, bool, and str classes available without importing anything. These classes are called built-in classes in Python. But, the Turtle class is not built-in. It must be imported from the turtle module.

In both examples the variable t is a reference that points to a Turtle object. The turtle object can be told to do things. Turtles understand certain messages or methods. We've already learned how to call methods on objects in Chap. 3. For instance, we've called the split method on a string object. Sending a message to a Turtle object is no different. For instance in Example 4.2 we sent the forward message to the turtle t passing 25 as the number of steps to move forward. The forward method, and other methods that turtles understand, are described in Chap. 13. Methods for the

TurtleScreen class are described in Chap. 14.

Practice 4.2 Write a short program that prompts the user to enter the number of sides of a regular polygon. Then draw a regular polygon with that many sides. You can use the textinput method described in Chap. 14 to get the input or you can just use input to get the input from the Debug I/O tab ofWing IDE 101.

While actual turtles are slow and perhaps not very interesting, turtle objects can be fun. A turtle object can be used in a lot of different ways. It can change color and width. It can be used to draw filled in shapes. It can draw circles and even display messages on the screen. Turtle graphics is a great way to become familiar with objectoriented programming. The best way to learn about object-oriented programming is just to have fun with it. Refer to Chap. 13 and use it to write some programs that draw some interesting pictures with color, interesting shapes, filled in polygons, etc.

Practice 4.3 Use the turtle module to write a program that draws a 4WD truck like that pictured in Fig. 4.2. A truck consists of two tires and a top of some sort. You should use some color. You may use penup and pendown while drawing. However, don't use goto once you have started drawing. The reason for this will become evident in the exercises at the end of the chapter.

You may want to change color, fill in shapes, etc. Be creative and try things out. Just be sure the last line of your program is screen.exitonclick(). Without the call to screen.exitonclick() the turtle graphics window may appear to freeze up.

Fig. 4.2 A 4WD truck

Found a mistake? Please highlight the word and press Shift + Enter  
< Prev   CONTENTS   Next >
Business & Finance
Computer Science
Language & Literature
Political science