Python 学习笔记

hide
Python 学习笔记
hide
Python 的语法特点

(Something strange ……)
leaf
代码缩进不再是美观的需要,而称为语法的一部分!
Arrow Link
leaf
函数的参数传递:支持关键字参数传递使参数顺序不再重要!
Arrow Link
leaf
内嵌代码中的帮助文档: DocStrings
Arrow Link
leaf
三引号的字符串
Arrow Link
leaf
while 循环和 for 循环可以带 else 语句块
Arrow Link
leaf
交换赋值:a,b = b,a
Arrow Link
leaf
Class 中 method(方法)的第一个参数非常特殊:需要声明(self),调用时却不提供(Python 自动添加)。
Arrow Link
leaf
类的构造函数名称为 __init__(self, ...)
Arrow Link
leaf
类的 Class 变量 和 Object 变量
Arrow Link
leaf
一切皆是对象:甚至字符串,变量,函数,都是对象
Arrow Link
hide
获得帮助
leaf
如何获得帮助?
leaf
1. 进入 python 命令行
leaf
2. 包含要查询的模组。如: import sys
leaf
3. 显示该模组包含的属性。命令: dir(sys)
leaf
4. 获取该模组的帮助。如: help(sys)
hide
源文件的字符集设置
leaf
为支持中文,需要在源码的第一行或第二行(一般是第二行)添加特殊格式的注释,声明源文件的字符集。默认为 7-bit ASCII
hide
格式为: # -*- coding: <encoding-name> -*-
leaf
参见: http://www.python.org/dev/peps/pep-0263/
leaf
如:设置 gbk 编码:



#!/usr/bin/python

# -*- coding: gbk -*-
leaf
如: 设置 utf-8 编码



#!/usr/bin/python

# -*- coding: utf-8 -*-
leaf
注: emacs 能够也能识别该语法。而 VIM 通过 # vim:fileencoding=<encoding-name> 来识别
hide
常量和变量
hide
变量
hide
变量名规则和 C 的相类似
leaf
合法的变量名,如: __my_name, name_23, a1b2_c3 等
hide
保留关键字(不能与之重名)
leaf
and      def     exec     if     not     return

assert    del     finally    import   or     try

break     elif     for     in     pass    while

class     else    from     is     print    yield

continue   except   global    lambda   raise
leaf
没有类型声明,直接使用
hide
类型综述 / 查看类型
hide
int
leaf
>>> type(17)

<type 'int'>
hide
float
leaf
>>> type(3.2)

<type 'float'>
hide
long
leaf
>>> type(1L)

<type 'long'>
leaf
>>> type(long(1))

<type 'long'>
hide
bool
leaf
True 和 False,注意大小写
leaf
>>> type(True)

<type 'bool'>
leaf
>>> type(1>2)

<type 'bool'>
hide
string
leaf
>>> type("Hello, World!")

<type 'str'>
hide
>>> type("WorldHello"[0])

<type 'str'>
leaf
即 Python 没有 Char 类型
hide
list
leaf
>>> type(['a','b','c'])

<type 'list'>
leaf
>>> type([])

<type 'list'>
hide
tuple
leaf
>>> type(('a','b','c'))

<type 'tuple'>
leaf
>>> type(())

<type 'tuple'>
hide
dict
leaf
>>> type({'color1':'red','color12':'blue'})

<type 'dict'>
leaf
>>> type({})

<type 'dict'>
hide
字符串
hide
三引号
leaf
三引号:''' 或者 """ 是 python 的发明。三引号可以包含跨行文字,其中的引号不必转义。(即内容可以包含的换行符和引号)
hide
leaf
'''This is a multi-line string. This is the first line.

This is the second line.

"What's your name?," I asked.

He said "Bond, James Bond."

'''
hide
单引号和双引号都可以用于创建字符串。
leaf
注意,单引号和双引号没有任何不同,不像 PHP, PERL
leaf
\ 作为转义字符,\ 用在行尾作为续行符
hide
r 或者 R 作为前缀,引入 Raw String
leaf
例如: r"Newlines are indicated by \n."
leaf
在处理常规表达式,尽量使用 Raw String,免得增加反斜线。例如 r'\1' 相当于 '\\1'。
hide
u 或者 U 作为前缀,引入 Unicode
leaf
例如: u"This is a Unicode string."
hide
u, r 可以一起使用,u在r前
hide
例如 ur"\u0062\n" 包含三个字符
leaf
\u0062
leaf
\\
leaf
n
hide
字符串连接:两个字符串并排,则表示两个字符串连接在一起
leaf
'What\'s ' "your name?" 自动转换为 "What's your name?" .
leaf
作用一:减少 \ 作为续行符的使用。
hide
作用二:可以为每段文字添加注释。如:
leaf
re.compile("[A-Za-z_]" # letter or underscore

"[A-Za-z0-9_]*" # letter, digit or underscore

)
hide
用括号包含多行字串
leaf
>>> test= ("case 1: something;" # test case 1

... "case 2: something;" #test case 2

... "case 3: something." #test case 3

... )

>>> test

'case 1: something;case 2: something;case 3: something.'

hide
类似于 sprintf 的字符串格式化
leaf
header1 = "Dear %s," % name
leaf
header2 = "Dear %(title)s %(name)s," % vars()
hide
字符串操作
hide
String slices
hide
[n] : 字符串的第 n+1 个字符
leaf
print "WorldHello"[0]
leaf
str="WorldHello"

print str[len(str)-1]
hide
[n:m] : 返回从 n 开始到 m 结束的字符串,包括 n, 不包括 m
leaf
>>> s = "0123456789"

>>> print s[0:5]

01234

>>> print s[3:5]

34

>>> print s[7:21]

789

>>> print s[:5]

01234

>>> print s[7:]

789

>>> print s[21:]

hide
len : 字符串长度
leaf
len("WorldHello")
hide
字符串比较
leaf
==, >, < 可以用于字符串比较
leaf
string 模组
Arrow Link
hide
警告: python 中字符串不可更改,属于常量
hide
# 错误!字符串不可更改

greeting = "Hello, world!"

greeting[0] = 'J' # ERROR!

print greeting
leaf
# 可改写为:

greeting = "Hello, world!"

newGreeting = 'J' + greeting[1:]

print newGreeting
hide
数字
hide
整形和长整形
leaf
longinteger ::= integer ("l" | "L")

integer ::= decimalinteger | octinteger | hexinteger

decimalinteger ::= nonzerodigit digit* | "0"

octinteger ::= "0" octdigit+

hexinteger ::= "0" ("x" | "X") hexdigit+

nonzerodigit ::= "1"..."9"

octdigit ::= "0"..."7"

hexdigit ::= digit | "a"..."f" | "A"..."F"
hide
浮点数
leaf
hide
类型转换
leaf
int("32")
leaf
int(-2.3)
leaf
float(32)
leaf
float("3.14159")
leaf
str(3.14149)
leaf
ord('A') : 返回 字母'A' 的 ASCII 值
leaf
复杂类型,如 list, tuple, dict 参见后面章节
Arrow Link
hide
局部变量与全局变量
leaf
函数中可以直接引用全局变量的值,无须定义。但如果修改,影响只限于函数内部。
leaf
函数中没有用 global 声明的变量是局部变量,不影响全局变量的取值
hide
global 声明全局变量
leaf
#!/usr/bin/python



def func1():

print "func1: local x is", x



def func2():

x = 2

print 'func2: local x is', x



def func3():

global x

print "func3: before change, x is", x

x = 2

print 'func3: changed x to', x



x = 1



print 'Global x is', x

func1()

print 'Global x is', x

func2()

print 'Global x is', x

func3()

print 'Global x is', x
hide
locals() 和 globals() 是两个特殊函数,返回局部变量和全局变量
leafhelp
locals() 返回局部变量的 copy,不能修改
leaf
globals() 返回全局变量的 namespace, 可以通过其修改全局变量本身
leaf
vars() 等同于 locales(),可以用 vars()['key'] = 'value' 动态添加局部变量
hide
复杂类型
leaf
string/unicode(字符串)
Arrow Link
hide
list (列表)
hide
方括号建立的列表
leaf
[10, 20, 30, 40]
leaf
["spam", "bungee", "swallow"]
leaf
["hello", 2.0, 5, [10, 20]]
hide
range 函数建立的列表
hide
>>> range(1,5)

[1, 2, 3, 4]
leaf
从1 到 5,包括1,但不包括5。(隐含步长为1)
hide
>>> range(10)

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
leaf
从 0 到 10,包括 0,但不包括 10。(隐含步长为1)
hide
>>> range(1, 10, 2)

[1, 3, 5, 7, 9]
leaf
步长为2
hide
访问列表中的元素
leaf
类似数组下标
leaf
print numbers[0]
leaf
numbers[1] = 5
hide
print 语句显示列表
leaf
vocabulary = ["ameliorate", "castigate", "defenestrate"]

numbers = [17, 123]

empty = []

print vocabulary, numbers, empty

['ameliorate', 'castigate', 'defenestrate'] [17, 123] []
hide
列表操作
hide
列表长度
leaf
len() 函数
hide
+ (相加)
leaf
>>> a = [1, 2, 3]

>>> b = [4, 5, 6]

>>> c = a + b

>>> print c

[1, 2, 3, 4, 5, 6]
hide
* (重复)
leaf
>>> [0] * 4

[0, 0, 0, 0]

>>> [1, 2, 3] * 3

[1, 2, 3, 1, 2, 3, 1, 2, 3]
hide
List slices
leaf
参见 String slices
Arrow Link
hide
列表是变量,可以更改
leaf
不像字符串 str, List 是可以更改的
leaf
>>> fruit = ["banana", "apple", "quince"]

>>> fruit[0] = "pear"

>>> fruit[-1] = "orange"

>>> print fruit

['pear', 'apple', 'orange']
leaf
>>> list = ['a', 'b', 'c', 'd', 'e', 'f']

>>> list[1:3] = ['x', 'y']

>>> print list

['a', 'x', 'y', 'd', 'e', 'f']
hide
列表中增加元素
leaf
>>> list = ['a', 'd', 'f']

>>> list[1:1] = ['b', 'c']

>>> print list

['a', 'b', 'c', 'd', 'f']

>>> list[4:4] = ['e']

>>> print list

['a', 'b', 'c', 'd', 'e', 'f']
hide
删除列表中元素
hide
通过清空而删除
leaf
>>> list = ['a', 'b', 'c', 'd', 'e', 'f']

>>> list[1:3] = []

>>> print list

['a', 'd', 'e', 'f']
hide
使用 del 关键字
leaf
>>> a = ['one', 'two', 'three']

>>> del a[1]

>>> a

['one', 'three']
leaf
>>> list = ['a', 'b', 'c', 'd', 'e', 'f']

>>> del list[1:5]

>>> print list

['a', 'f']
hide
查看列表的id
leaf
>>> a = [1, 2, 3]

>>> b = [1, 2, 3]

>>> print id(a), id(b)

418650444 418675820

>>> b = a

>>> print id(a), id(b)

418650444 418650444

>>> b = a[:]

>>> print id(a), id(b)

418650444 418675692
hide
引用和Copy/Clone
leaf
b = a,则两个变量指向同一个对象,两个变量的值一起变动
Arrow Link
leaf
b = a[:],则建立克隆,b 和 a 指向不同对象,互不相干
Arrow Link
leaf
list 作为函数的参数,是引用调用,即函数对 list 所做的修改会影响 list 对象本身
hide
列表嵌套和矩阵
hide
嵌套
leaf
>>> list = ["hello", 2.0, 5, [10, 20]]

>>> list[3][1]

20
hide
矩阵
leaf
>>> matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

>>> matrix[1]

[4, 5, 6]

>>> matrix[1][1]

5
hide
字符串和列表
hide
string.split 方法
leaf
>>> import string

>>> song = "The rain in Spain..."

>>> string.split(song)

['The', 'rain', 'in', 'Spain...']
leaf
>>> string.split(song, 'ai')

['The r', 'n in Sp', 'n...']
hide
string.join 方法
leaf
>>> list = ['The', 'rain', 'in', 'Spain...']

>>> string.join(list)

'The rain in Spain...'
leaf
>>> string.join(list, '_')

'The_rain_in_Spain...'
leaf
>>> list = ['The', 'rain', 'in', 'Spain...']

>>> '|'.join(list)

'The|rain|in|Spain...'
hide
Tuples
hide
圆括号建立 Tuple
hide
在最外面用圆括号括起来
leaf
>>> type((1,2,3))

<type 'tuple'>
hide
必需是逗号分隔的多个值
leaf
>>> type((1))

<type 'int'>
leaf
>>> type((1,))

<type 'tuple'>
leaf
>>> type(('WorldHello'))

<type 'str'>
leaf
>>> type(('WorldHello',))

<type 'tuple'>
hide
Tuple vs list
leaf
Tuple 和 list 的区别就是: Tuple 是不可更改的,而 list 是可以更改的
hide
一个元素也可以构成 list,但 tuple 必需为多个元素
leaf
>>> type([1])

<type 'list'>
leaf
>>> type((1))

<type 'int'>
hide
Dictionaries (哈希表)
hide
花括号建立 哈希表
leaf
Perl 管这种类型叫做 哈希表 或者关联数组。即下标可以是字符串的数组
leaf
>>> eng2sp = {}

>>> eng2sp['one'] = 'uno'

>>> eng2sp['two'] = 'dos'

>>> print eng2sp

{'one': 'uno', 'two': 'dos'}
hide
访问哈希表中元素:下标为字符串
leaf
>>> print eng2sp

{'one': 'uno', 'three': 'tres', 'two': 'dos'}

>>> print eng2sp['two']

'dos'
hide
哈希表操作
hide
keys() 方法,返回 keys 组成的列表
leaf
>>> eng2sp.keys()

['one', 'three', 'two']
hide
values() 方法,返回由 values 组成的列表
leaf
>>> eng2sp.values()

['uno', 'tres', 'dos']
hide
items() 方法,返回由 key-value tuple 组成的列表
leaf
>>> eng2sp.items()

[('one','uno'), ('three', 'tres'), ('two', 'dos')]
leaf
from MoinMoin.util.chartypes import _chartypes

for key, val in _chartypes.items():

if not vars().has_key(key):

vars()[key] = val
hide
haskey() 方法,返回布尔值
leaf
>>> eng2sp.has_key('one')

True

>>> eng2sp.has_key('deux')

False
hide
get() 方法
hide
返回哈希表某个 key 对应的 value
leaf
如 eng2sp.get('one')
leaf
等同于 eng2sp['one']
hide
get() 可以带缺省值,即如果没有定义该 key,返回缺省值
leaf
如 eng2sp.get('none', 0),如果没有定义 none, 返回 0,而不是空
hide
引用和 copy/clone
hide
哈希表的克隆:copy() 方法
leaf
>>> opposites = {'up': 'down', 'right': 'wrong', 'true': 'false'}

>>> copy = opposites.copy()
leaf
Iterators
hide
type 函数返回变量类型
leaf
isinstance(varname, type({}))
hide
语句
leaf
每一行语句,不需要分号作为语句结尾!
leaf
如果多个语句写在一行,则需要 分号 分隔;
hide
用 “\” 显示连接行
leaf
如:

i=10

print \

i
hide
默认连接行
leaf
方括号,圆括号,花括号中的内容可以多行排列,不用 \ 续行,默认续行
leaf
例如:

month_names = ['Januari', 'Februari', 'Maart', # These are the

'April', 'Mei', 'Juni', # Dutch names

'Juli', 'Augustus', 'September', # for the months

'Oktober', 'November', 'December'] # of the year
hide
缩进
leaf
一条语句前的空白(空格、TAB)是有意义的!
leaf
相同缩进的语句成为一个逻辑代码块
leaf
错误的缩进,将导致运行出错!
leaf
缩进的单位是空格。Tab 转换为1-8个空格,转换原则是空格总数是 8 的倍数。
hide
空语句 pass
leaf
def someFunction():

pass
hide
操作符和表达式
hideidea
** 代表幂
leaf
3 ** 4 gives 81 (i.e. 3 * 3 * 3 * 3)
hideidea
// 代表 floor
leaf
4 // 3.0 gives 1.0
hide
% 代表取余
leaf
-25.5 % 2.25 gives 1.5 .
leaf
<< 左移位
leaf
>> 右移位
leaf
<, >, <=, >=, ==, != 和 C 类似
hideidea
比较可以级联。如:
leaf
if 0 < x < 10:

print "x is a positive single digit."
Arrow Link
hide
~, &, |, ^ 和 c 语言相同
leaf
5 & 3 gives 1.
leaf
5 | 3 gives 7.
leaf
5 ^ 3 gives 6
hide
~5 gives -6
leaf
取反。 ~x 相当于 -(x+1)
hide
and, or, not 代表逻辑与或非
leaf
if 0 < x and x < 10:

print "x is a positive single digit."
hideidea
is 和 is not,用于 比较 两个 object 是否为同一个对象
leaf
实际上两个对象的 ID 相同,才代表同一个对象。
leaf
is: id(obj1) == id(obj2)
leaf
is not: id(obj1) != id(obj2)
hideidea
in, not in 用于测试成员变量
leaf
'a' in ['a', 'b', 'c'] # True
hideidea
交换赋值 a,b = b,a
hide
为交换变量 a, b 的值,其它语言可能需要一个中间变量
leaf
temp=a

a=b

b=temp
leaf
python 有一个交换赋值的写法: a,b = b,a
hide
控制语句
hide
if 语句
hide
if ... elif ... else , 示例:(注意冒号和缩进)
leaf
#!/usr/bin/python

# Filename : if.py

number = 23

guess = int(raw_input('Enter an integer : '))

if guess == number:

print 'Congratulations, you guessed it.' # new block starts here

print "(but you don't win any prizes!)" # new block ends here

elif guess < number:

print 'No, it is a little higher than that.' # another block

# You can do whatever you want in a block ...

else:

print 'No, it is a little lower than that.'

# you must have guess > number to reach here

print 'Done'

# This last statement is always executed, after the if statement

# is executed.
leaf
注意: 没有 switch... case 语句!
hide
while 循环语句
hide
while ... [else ...] ,示例:(else 可选)
leaf
#!/usr/bin/python

# Filename : while.py

number = 23

stop = False

while not stop:

guess = int(raw_input('Enter an integer : '))

if guess == number:

print 'Congratulations, you guessed it.'

stop = True # This causes the while loop to stop

elif guess < number:

print 'No, it is a little higher than that.'

else: # you must have guess > number to reach here

print 'No, it is a little lower than that.'

else:

print 'The while loop is over.'

print 'I can do whatever I want here.'

print 'Done.'
hide
break 和 continue 语句
leaf
break 语句跳出循环,且不执行 else 语句
hide
for 循环语句
hide
for... else... ,示例:(else 可选)
hide
#!/usr/bin/python

# Filename : for.py

for i in range(1, 5):

print i

else:

print 'The for loop is over.'
leaf
range(1,5) 相当于 range(1,5,1) 第三个参数为步长
Arrow Link
leaf
range 止于第二个参数,但不包括第二个参数
hide
break 和 continue 语句
leaf
break 语句跳出循环,且不执行 else 语句
hide
后置 for 语句
leaf
[ name for name in wikiaction.__dict__ ]
leaf
actions = [name[3:] for name in wikiaction.__dict__ if name.startswith('do_')]
hide
示例
hide
字符串中的字符
leaf
prefixes = "JKLMNOPQ"

suffix = "ack"

for letter in prefixes:

print letter + suffix
hide
函数
hide
函数声明
hide
def 关键字
leaf
函数名
leaf
括号和参数
leaf
冒号
hide
如:
leaf
#!/usr/bin/python

# Filename : func_param.py

def printMax(a, b):

if a > b:

print a, 'is maximum'

else:

print b, 'is maximum'

printMax(3, 4) # Directly give literal values
hide
参数的缺省值
hide
如同 C++ 那样
leaf
#!/usr/bin/python

# Filename : func_default.py

def say(s, times = 1):

print s * times

say('Hello')

say('World', 5)
hide
关键字参数
leaf
在 C++ 等语言中遇到如下困扰:有一长串参数,虽然都有缺省值,但只为了修改后面的某个参数,还需要把前面的参数也赋值。这种方式,在 python 中称为顺序参数赋值。
leaf
Python 的一个特色是关键字参数赋值
hide
例如:
leaf
#!/usr/bin/python

# Filename : func_key.py



def func(a, b=5, c=10):

print 'a is', a, 'and b is', b, 'and c is', c



func(3, 7)

func(25, c=24)

func(c=50, a=100)
hide
可变参数
leaf
参数前加 * 或者 **,则读取的是 list 或者 dictionary
hide
示例1
leaf
#!/usr/bin/python



def sum(*args):

'''Return the sum the number of args.'''

total = 0

for i in range(0, len(args)):

total += args[i]

return total



print sum(10, 20, 30, 40, 50)
hide
函数返回值
leaf
return 语句提供函数返回值
leaf
没有 return,则返回 None
hide
DocStrings
hide
DocStrings 提供函数的帮助
leaf
函数内部的第一行开始的字符串为 DocStrings
hide
DocStrings 一般为多行
leaf
DocString 为三引号扩起来的多行字符串
leaf
第一行为概述
leaf
第二行为空行
leaf
第三行开始是详细描述
hide
DocStrings 的存在证明了函数也是对象
leaf
函数的 __doc__ 属性为该 DocStrings
leaf
例如 print printMax.__doc__ 为打印 printMax 函数的 DocStrings
leaf
help( ) 查看帮助就是调用函数的 DocStrings
hide
Lambda Forms
leaf
Lambda Forms 用于创建并返回新函数,即是一个函数生成器
hide
示例
leaf
hide
内置函数和对象
leaf
帮助: import __builtin__; help (__builtin__)
hide
函数
hide
数学/逻辑/算法
leaf
abs(number) : 绝对值
leaf
cmp(x,y) : 比较x y 的值。返回 1,0,-1
leaf
divmod(x, y) -> (div, mod) : 显示除数和余数
leaf
pow(x, y[, z]) -> number
leaf
round(number[, ndigits]) -> floating point number : 四舍五入,保留 n 位小数
leaf
sum(sequence, start=0) -> value : 取 sequence 的和
leaf
hex(number) -> string : 返回十六进制
leaf
oct(number) -> string : 八进制
leaf
len(object) -> integer
leaf
max(sequence) -> value
leaf
min(sequence) -> value
hide
range([start,] stop[, step]) -> list of integers
leaf
>>> range(10)

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
hide
filter(function or None, sequence) -> list, tuple, or string
leaf
function 作用于 sequence 的每一个元素,返回 true 的元素。返回类型同 sequence 类型。
leaf
如果 function 为 None,返回本身为 true 的元素
hide
map(function, sequence[, sequence, ...]) -> list
leaf
将函数作用于 sequence 每个元素,生成 list
leaf
>>> map(lambda x : x*2, [1,2,3,4,5])

[2, 4, 6, 8, 10]
hide
reduce(function, sequence[, initial]) -> value
leaf
从左至右,将函数作用在 sequence 上,最终由 sequence 产生一个唯一值。
leaf
>>> reduce(lambda x, y: x+y, [1, 2, 3, 4, 5])

15

相当于 ((((1+2)+3)+4)+5)
leaf
sorted(iterable, cmp=None, key=None, reverse=False) : 排序
hide
zip(seq1 [, seq2 [...]]) -> [(seq1[0], seq2[0] ...), (...)]
leaf
>>> zip('1234','789')

[('1', '7'), ('2', '8'), ('3', '9')]
hide
coerce(x, y) -> (x1, y1)
leaf
Return a tuple consisting of the two numeric arguments converted to a common type, using the same rules as used by arithmetic operations. If coercion is not possible, raise TypeError.
hide
字符串
leaf
chr(i) : 0<=i<256, 返回 ascii 码为 i 的字符
leaf
unichr(i) -> Unicode character : 返回 unicode 。 0 <= i <= 0x10ffff
leaf
ord(c) : 返回字符 c 的 ascii 码
hide
对象相关
hide
delattr(object,name) : 在对象 object 中删除属性 name
leaf
delattr(x, 'y') 相当于 del x.y
hide
getattr(object, name[, default]) -> value
leaf
getattr(x, 'y') 相当于 x.y
leaf
缺省值,是当对象不包含时的取值
leaf
hasattr(object, name) -> bool
leaf
id(object) -> integer : 返回对象 ID,相当于内存中地址
leaf
hash(object) -> integer : 两个对象具有相同的值,就有相当的 hash。但反之未必。
leaf
setattr(object, name, value) : 相当于赋值 x.y = v
leaf
isinstance(object, class-or-type-or-tuple) -> bool
leaf
issubclass(C, B) -> bool
leaf
globals() -> dictionary
leaf
locals() -> dictionary
hide
vars([object]) -> dictionary
leaf
没有参数相当于 locals()
leaf
以对象为参数,相当于 object.__dict__
leaf
dir([object]) : 显示对象属性列表
leaf
repr(object) -> string : 对象 object 的正式名称
leaf
reload(module) -> module : 重新加载 module
hide
iter
hide
iter(collection) -> iterator
leaf
Get an iterator from an object. In the first form, the argument must

supply its own iterator, or be a sequence.
hide
iter(callable, sentinel) -> iterator
leaf
In the second form, the callable is called until it returns the sentinel.
hide
输入输出
leaf
input([prompt]) -> value : 输入。相当于 eval(raw_input(prompt))。
leaf
raw_input([prompt]) -> string : 输入内容不做处理,作为字符串
hide
其他
hide
__import__(name, globals, locals, fromlist) -> module : 动态加载模块
leaf
import module 中的 module 不能是变量。如果要使用变量动态加载模块,使用下面的方法。
leaf
def importName(modulename, name):

""" Import name dynamically from module



Used to do dynamic import of modules and names that you know their

names only in runtime.



Any error raised here must be handled by the caller.



@param modulename: full qualified mudule name, e.g. x.y.z

@param name: name to import from modulename

@rtype: any object

@return: name from module

"""

module = __import__(modulename, globals(), {}, [name])

return getattr(module, name)
leaf
callable(object) : 是否可调用,如函数。对象也可以调用。
leaf
compile(source, filename, mode[, flags[, dont_inherit]]) -> code object
hide
eval(source[, globals[, locals]]) -> value
leaf
执行代码,source 可以是字符串表达的代码,或者 compile 返回的 code object
leaf
execfile(filename[, globals[, locals]])
leaf
intern(string) -> string
hide
对象
hide
basestring
leaf
str
leaf
unicode
leaf
buffer
leaf
classmethod
leaf
complex
leaf
dict
leaf
enumerate
leaf
file
leaf
file
leaf
float
leaf
frozenset
hide
int
leaf
bool
leaf
list
leaf
long
leaf
property
leaf
reversed
leaf
set
leaf
slice
leaf
staticmethod
leaf
super
leaf
tuple
leaf
type
leaf
xrange
hide
输入和输出
hide
输入:raw_input vs input
hide
最好用 raw_input
leaf
name = raw_input ("What...is your name? ")
hide
input 只能用于输入数字
leaf
age = input ("How old are you? ")
leaf
如果输入的不是数字,直接报错退出!
hide
文件
hide
打开文件
hide
leaf
>>> f = open("test.dat","r")
hide
leaf
>>> f = open("test.dat","w")

>>> print f

<open file 'test.dat', mode 'w' at fe820>
hide
write("content"):写文件
leaf
>>> f.write("Now is the time")

>>> f.write("to close the file")
hide
read(count):读文件
hide
读取全部数据
leaf
>>> text = f.read()

>>> print text

Now is the timeto close the file
hide
读取定长数据
leaf
>>> f = open("test.dat","r")

>>> print f.read(5)

Now i
leaf
判断是否到文件尾:读取内容为空
leaf
readline():读取一行内容,包括行尾换行符
leaf
readlines():读取每行内容到一个列表
hide
关闭文件
leaf
>>> f.close()
hide
示例
leaf
def copyFile(oldFile, newFile):

f1 = open(oldFile, "r")

f2 = open(newFile, "w")

while True:

text = f1.read(50)

if text == "":

break

f2.write(text)

f1.close()

f2.close()

return
hide
% 格式化输出
leaf
% 用在数字中,是取余数。
leaf
% 前面如果是字符串,则类似 C 的 printf 格式化输出。
hide
示例
leaf
>>> cars = 52

>>> "In July we sold %d cars." % cars

'In July we sold 52 cars.'
leaf
>>> "In %d days we made %f million %s." % (34,6.1,'dollars')

'In 34 days we made 6.100000 million dollars.'
hide
pickle 和 cPickle
leaf
相当于 C++ 中的序列化
hide
示例
leaf
>>> import pickle

>>> f = open("test.pck","w")

>>> pickle.dump(12.3, f)

>>> pickle.dump([1,2,3], f)

>>> f.close()



>>> f = open("test.pck","r")

>>> x = pickle.load(f)

>>> x

12.3

>>> type(x)

<type 'float'>

>>> y = pickle.load(f)

>>> y

[1, 2, 3]

>>> type(y)

<type 'list'>
hide
使用 cPickle
leaf
cPickle 是用 C 语言实现的,速度更快