[: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.

把你的文件用以 .py 结尾的文件名保存可以使他成为Python的组件。一旦你拥有了一个组件,你的代码就可以在解释器被用到,或者被别的文件和程序用到。

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

把这个文件保存在 examples/ 目录下,并且起名叫 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:

添加这些髙亮的行到 message.py 中以匹配这些:

   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()

变量 msg 是组件级别或者全局变量。当第一次运行函数时,msg是空的并且程序会跳过调用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.

使用全局变量,类似于from foo import *,通常被看作是不好的形式。

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