[:StartProgramming: （首页）开始编程之旅] 翻译自Lee Harr的[http://staff.easthighschool.net/lee/computers/book/Start_Programming.html Start Programming] 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:
Save the file in the examples/ directory and call it message.py
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?
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:
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.