(首页)开始编程之旅 翻译自Lee Harr的Start Programming

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

1. StartProgramming-2-3 命名空间Namespaces

Notice that when you use

注意当你用这个时

   1 import random

You must access the functions in random by the full name:

你必须用全名访问函数random:

   1 random.randrange(1, 11)

The modules are said to have their own namespaces. This allows you to call on a particular piece of the module with no chance for any confusion. It is kind of like in a classroom where a teacher may need to call on "Joe Smith" or on "Joe Brown" in order to specify which Joe is being called.

这个组件表明他们拥有自己的 命名空间。这就允许你在组件中调用一个详细的部分并且不会造成任何混乱。这就像在一个教室中一个老师可以叫"Joe Smith"或者"Joe Brown"来代替叫的是哪个"Joe"。

1.1. from

If you only need one particular function from a module, you can import that function directly:

如果你在组件中只需要一个具体的函数,你可以直接导入这个函数:

   1 from random import randrange
   2 randrange(1, 11)

It is sort of like the kid in the class named "Ferdinand" who almost certainly will not have a classmate named Ferdinand, or just calling on "Joe" when Joe Smith is out sick for the day.

这就好比是在班级中,没有和"Ferdinand"同名的同学,或者今天当"Joe Smith"生病不在时正好叫到"Joe"。

You probably noticed that we do something like this all the time to start up the penguin graphics mode:

你大概注意到我们启动企鹅图形方式时总是做像这样的事情:

   1 from penguin import *

The * says to import everything from the penguin module.

这个*意思是从企鹅组件中导入所有的东西。

To see exactly what is being imported, try this:

要准确地看到导入了什么,试试这个:

Restart Python, to get a fresh start, then:

重新启动Python,获得一个新鲜的开始,然后:

   1 dir()
   2 from penguin import *
   3 dir()

Normally, it is considered bad style to import everything from a module. As you can see it may introduce a huge number of names in to the local namespace, but in this case the module is meant to be used on its own, and there is a definite advantage to being able to type "forward(50)" instead of "pete.forward(50)"

一般情况下,从一个组件中导入所有的东西不是一个好的方式。这样你就会看到在当前的命名空间中插入了大量的名字,但在这种情况下组件只打算被用在自身上,并且用"pete.forward(50)"代替"forward(50)"可以使初学者取得更加明确的优势。

1.2. locals, globals, builtins

Python has 3 namespaces. The local namespace is inside of a function and is the first place checked to find a particular name. The global namespace is inside of a module, and is next in line for name resolution. Finally, the builtin namespace holds things which should be available everywhere, and is the last place searched for names.

Python有3个命名空间。局部命名空间是在函数的内部并且首先会在这里查找一个指定的名字。全局命名空间在一个组件内部,并且这是接下来要查找名字的地方。最后,内置命名空间在任何时候都会保持一些事物,并且这里是查找名字最后的地方。