[:StartProgramming: (首页)开始编程之旅] 翻译自Lee Harr的[http://staff.easthighschool.net/lee/computers/book/Start_Programming.html Start Programming]

本文是使用[http://www.nongnu.org/pygsear/ pygsear]+[http://pygame.org pygame]作为开发环境,以初级用户角度来分步分阶段学习[http://www.python.org PYTHON]基本概念,并以小游戏开发项目为具体案例,介绍的十分详细。编写风格清新朴实,没有象一般教科书那样枯燥,极其适合初级用户来激发兴趣时使用。 TableOfContents

1. StartProgramming-2-4 Functions

The interactive python interpreter is very useful if you are testing and typing just a few lines, but anything more than that and you are going to want to save your code in a file.

Saving your code in a file that ends in .py makes it a Python module. Once you have a module, your code can be used from the interpreter, or by code in other files and programs.

The Python code that you save to a file will look much like the code you typed directly in to the interpreter. Try it now.

Create a new, blank file in your text editor. In that file, type these lines:

   1 from pygsear.Drawable import String
   3 def send(new_msg):
   4     m = String(message=new_msg, fontSize=80)
   5     m.center()
   6     m.udraw()

Save the file in the examples/ directory and call it message.py

1.1. import

When you try to import a module, Python will look first in the current directory. It looks for a file with the name of the module plus a .py ending.

Start Python in the examples/ directory, and import your new module:

   1 import message

To use your new module, call the send() function with a text message:

   1 message.send('Penguin Patrol!')

But there is a problem with this. What happens if you call the function again?

   1 message.send('Python & Pygame. Oh yea!')
   2 message.send('Take me to your leader')

1.2. global

One way to fix the problem of the new message writing over the previous one is to keep a handle on the old String object. That way when the function is called again, we can erase the old message and make a new one.

Add the highlighted lines to your message.py so it matches this:

   1 from pygsear.Drawable import String
   3 msg = None
   5 def send(new_msg):
   6     global msg
   7     if msg is not None:
   8         msg.uclear()
   9     m = String(message=new_msg, fontSize=80)
  10     m.center()
  11     m.udraw()
  12     msg = m

The variable msg is a module level or global variable. The first time through the function, msg will be None and we will skip the call to uclear()

On any other call, we first clear out the old message, then draw the new one and save it as msg

Using global variables, sort of like from foo import *, is usually considered bad form.

A much better solution is to use a class which we will work on next.