Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1798286
  • 博文数量: 335
  • 博客积分: 4690
  • 博客等级: 上校
  • 技术积分: 4341
  • 用 户 组: 普通用户
  • 注册时间: 2010-05-08 21:38
个人简介

无聊之人--除了技术,还是技术,你懂得

文章分类

全部博文(335)

文章存档

2016年(29)

2015年(18)

2014年(7)

2013年(86)

2012年(90)

2011年(105)

分类: Python/Ruby

2011-06-14 18:33:03

3.4. Declaring variables

变量声明

Now that you know something about dictionaries, tuples, and lists (oh my!), let's get back to the sample program from Chapter 2, odbchelper.py.

现在,你已经对字典,tuple,和列表有所了解(哦,我的天哪),那让我们回到第二章的样例程序 odbchelper.py           

Python has local and global variables like most other languages, but it has no explicit variable declarations. Variables spring into existence by being assigned a value, and they are automatically destroyed when they go out of scope.

同其它主流语言一样,Python也有局部变量和全局变量,但是这些变量不需要显示的声明。当一个变量被赋值的时候,变量就开始存在,当超出范围时,变量被自动销毁。

Example 3.17. Defining the myParams Variable

3.17 定义myParmas 变量

  1. if __name__ == "__main__":
  2.     myParams = {"server":"mpilgrim", \
  3.                 "database":"master", \
  4.                 "uid":"sa", \
  5.                 "pwd":"secret" \
  6.                 }

Notice the indentation. An if statement is a code block and needs to be indented just like a function.

注意缩进。一个if语句就是一个代码块,它也如同函数一样,需要缩进。

Also notice that the variable assignment is one command split over several lines, with a backslash (“\”) serving as a line-continuation marker.

同时值得注意的是变量赋值是一个命令,可以分为好几行,反斜杠(backslash \’)是一个续行标记。

Note

 

When a command is split among several lines with the line-continuation marker (“\”), the continued lines can be indented in any manner; Python's normally stringent indentation rules do not apply. If your Python IDE auto-indents the continued line, you should probably accept its default unless you have a burning reason not to.

当一个命令通过一个续行符’\’分为好几行时,紧接着的行可以以任意方式缩进。Python通常严格字符缩进规则是不适用的。如果你的PythonIDE自动缩进后续行,你或许可以接受默认缩进值,除非你有必要的理由不这么做。

 

Strictly speaking, expressions in parentheses, straight brackets, or curly braces (like defining a dictionary) can be split into multiple lines with or without the line continuation character (“\”). I like to include the backslash even when it's not required because I think it makes the code easier to read, but that's a matter of style.

严格来说,在括号(),方括号[],大括号{}(比如定义字典),中的表达式都可以分成多行,续行符可要可不要。我个人更倾向于使用续行符而不管是否需要,这是因为添加续行符后,代码具有很好的可读性,但是这仅仅是个人的编程风格。

Third, you never declared the variable myParams, you just assigned a value to it. This is like VBScript without the option explicit option. Luckily, unlike VBScript, Python will not allow you to reference a variable that has never been assigned a value; trying to do so will raise an exception.

第三,你根本不需要声明变量myParams,你所作的就是给它赋值。这就像VB脚本中不需要显示的使用option explicit 选项。

3.4.1. Referencing Variables

3.4.1引用变量

Example 3.18. Referencing an Unbound Variable

3.18 引用一个未绑定(未赋值)的变量

  1. >>> x
  2. Traceback (innermost last):
  3.   File "", line 1, in ?
  4. NameError: There is no variable named 'x'
  5. >>> x = 1
  6. >>> x
  7. 1

You will thank Python for this one day.

总有一天对于这一点你会感谢Python

3.4.2. Assigning Multiple Values at Once

同时给变量赋多个值

One of the cooler programming shortcuts in Python is using sequences to assign multiple values at once.

Python中有一个非常酷的变量赋值方法:使用序列同时赋多个值给变量

Example 3.19. Assigning multiple values at once

3.19 同时给变量赋多个值

  1. >>> v = ('a', 'b', 'e')
  2. >>> (x, y, z) = v
  3. >>> x
  4. 'a'
  5. >>> y
  6. 'b'
  7. >>> z
  8. 'e'

1

v is a tuple of three elements, and (x, y, z) is a tuple of three variables. Assigning one to the other assigns each of the values of v to each of the variables, in order.

V是一个包含3个元素的tuple,而(x,y,z)是一个含有三个变量的tuple

将一个tuple赋值给另外一个tuple,会将v中没有元素按顺序赋值给tuple中的变量。

This has all sorts of uses. I often want to assign names to a range of values. In C, you would use enum and manually list each constant and its associated value, which seems especially tedious when the values are consecutive. In Python, you can use the built-in range function with multi-variable assignment to quickly assign consecutive values.

赋多值有各种各样的方法。我通常将一个区间的值赋值给一个变量。在C中,你可能是使用枚举数据类型(enum),这通常需要你手工的列出每一个常量,每一个常量都与一个值相关联当这些值是连续的时候,你的操作可能回看起来很无聊。而在Python中,你可以使用内置的range函数给多个变量快速的多个连续值。

Example 3.20. Assigning Consecutive Values

3.20 变量赋连续值

  1. >>> range(7)
  2. [0, 1, 2, 3, 4, 5, 6]
  3. >>> (MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY) = range(7)
  4. >>> MONDAY
  5. 0
  6. >>> TUESDAY
  7. 1
  8. >>> SUNDAY
  9. 6

1

The built-in range function returns a list of integers. In its simplest form, it takes an upper limit and returns a zero-based list counting up to but not including the upper limit. (If you like, you can pass other parameters to specify a base other than 0 and a step other than 1. You can print range.__doc__ for details.)

内置的range函数返回一个有整数组成的列表。它的最简单的形式,它接受一个整数作为上限,返回一个从0开始连续计数但是不包括上限的列表。(如果你喜欢,你可以提供其他的参数来明确说明区间的起点和步长,而不是采用默认值01.你可以打印range.__doc__来获取详细的消息。

2

MONDAYTUESDAYWEDNESDAYTHURSDAYFRIDAYSATURDAY, and SUNDAY are the variables you're defining. (This example came from the calendar module, a fun little module that prints calendars, like the UNIX program cal. The calendar module defines integer constants for days of the week.)

MONDAYTUESDAYWEDNESDAYTHURSDAYFRIDAYSATURDAY, and SUNDAY 是你定义的变量。(这个例子说明日历模型,一个小而有趣的能打印日历的模块,同Unix程序 cal类似。这个日历模块将每周的每一天定义为整型常量。

3

Now each variable has its value: MONDAY is 0TUESDAY is 1, and so forth.

每一个变量都有自己的值,MONDAY 的值为0TUESDAY的值为1,以此类推。

You can also use multi-variable assignment to build functions that return multiple values, simply by returning a tuple of all the values. The caller can treat it as a tuple, or assign the values to individual variables. Many standard Python libraries do this, including the os module, which you'll discuss in Chapter 6.

你可以使用多个变量赋值技巧来构建能返回多个值得函数,最简单的就是返回tuple的所有元素。调用者可以它视作一个tuple,或是将这些返回值赋给一个单独的变量。许多标准的Python程序库就返回多个值,包括我们将在第六章讨论的os模块。

 

阅读(851) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~