python学习笔记电子书

程序输入和raw_inoput() 内建函数


字符解释


f% :对应小数

>>> print "%s is number %d" % ("python",1)
python is number 1

>>> user = raw_input('enter login name:')
enter login name:root

>>> print 'ur login is:', user
your login is: root


>>> num = raw_input('now enter a number:')
now enter a number:1024
>>> print 'doubling your number: %d' % (int(num)*2)
doubling your number: 2048

>>> help(raw_input)

运算符


/ :取余数
// :浮点除法

** :乘方运算符

>>> print -2*4 + 3**2
1

变量和赋值


>>> miles = 1000.0
>>> kilometers = 1.609 * miles
>>> print '%f miles is the same as %f km' % (miles, kilometers)
1000.000000 miles is the same as 1609.000000 km


增量赋值

n = n * 10

n *=10

数字


int(有符号整数)
long(长整数)
bool(布尔值)
float(浮点值)
complex(复数)

字符串


>>> pystr = 'python'
>>> pystr[0]
'p'

>>> iscool = 'is cool'
>>> pystr = 'python'
>>> pystr[2:5]
'tho'
>>> iscool[:2]
'is'
>>> iscool[:3]
'is '
>>> iscool[-1]
'l'
>>> pystr + iscool
'pythonis cool'

>>> pystr+ ' ' + iscool
'python is cool'
>>> pystr * 2
'pythonpython'
>>> '-' * 20
'--------------------'


>>> pystr = '''python
... is cool'''
>>> pystr
'python\nis cool'
>>> print pystr
python
is cool


列表和元组

>>> alist = [1,2,3,4]
>>> alist
[1, 2, 3, 4]
>>> alist[0]
1


>>> atuple = ('robots', 77,93,'try')
>>> atuple
('robots', 77, 93, 'try')
>>> atuple[:3]
('robots', 77, 93)


字典


>>> adict = {'host':'earth'}
>>> adict['port']=80
>>> adict
{'host': 'earth', 'port': 80}


>>> adict.keys()
['host', 'port']

2.1 代码块及缩进对齐


2.11 if语句


while 循环

for 循环和range内建函数


>>> for eachnum in [0,1,2]:
... print eachnum
...
0
1
2


>>> for eachnum in range(3):
... print eachnum
...
...
0
1
2


>>> foo = 'abc'
>>> for c in foo:
... print c
...
a
b
c

len()----索引值

foo = 'abc'
for i in range(len(foo)):
print foo[i], '(%d)' % i

2.13 列表解析


squared = [x ** 2 for x in range(4)]
for i in squared:
print i


G:\python安装到这里\python.exe C:/Users/Administrator/teat2.py
0
1
4
9


2.15 文件和内建函数open()、file()


如何打开文件

handle = open(file_name, access_mode = 'r')

2.16 错误和异常

2.17 函数

如何定义函数


def function_name([arguments]):
"optional documentation string"
function_suide


如何调用函数

def addMe2Me(x):
"apply + operation to argument"
return (x + x)
addMe2Me(10)

默认参数


def foo(debug=True):
'determine if debug mode with default argument'
if debug:
print 'in debug mode'
print 'done'
foo()


G:\python安装到这里\python.exe C:/Users/Administrator/teat2.py
in debug mode
done

def foo(debug=True):
'determine if debug mode with default argument'
if debug:
print 'in debug mode'
print 'done'
foo(False)

G:\python安装到这里\python.exe C:/Users/Administrator/teat2.py

进程已结束,退出代码0


2.18 类


如何定义类 ---python 不用,以后详解

class ClassName(base_class[es]):
"option documention string"
static_member_declarations
method_declarations


如何创建实例 13章详解

2.19 模块


import sys
sys.stdout.write('hello word\n')

G:\python安装到这里\python.exe C:/Users/Administrator/teat2.py
hello word


>>> import sys
>>> sys.version
'2.7.10 (default, May 23 2015, 09:40:32) [MSC v.1500 32 bit (Intel)]'

2.19 实用的函数


第三章 python 基础

3.1 语句和语法


反斜杠 \ 继续上一行
分号: 将两个语句连接在一起
冒号: 将代码块的头和体分开
缩进


3.11 注释

3.12 继续(\)

一行过长的语句可以使用反斜杠分解成几行。

多个语句构成代码组(:): 如 if while

同一行书写多个语句(;)


3.16 模块


3.2 变量赋值 等于号


增量赋值

x = x + 1 x +=1

多重赋值


x = y =z =1


多个赋值


x,y,z = 1,2, 'a string'

(x,y,z) = (1,2, 'a string')


交换两个变量

>>> x,y = 1,2
>>> x
1
>>> y
2
>>> x,y = y,x
>>> x
2
>>> y
1


标示符


3.3.2 关键字

for in or


3.4.1 模块结果和布局

1、起始行

2、模块文档

3、模块导入

4、变量定义

5、类定义

6、函数定义

7、主程序


3.4.2 在主程序中写测试代码

3.5.1 变量定义


3.5.4 引用计数


增加引用计数


减少引用计数


3.6 第一个python程序

第四章 python 对象

4.3.1 类型对象和type 类型对象


4.4 内部类型


4.4.1 代码对象

4.4.2 帧对象

4.4.3 跟踪记录 对象

4.4.4 切片对象

4.5 对象的比较值


4.5 标准类型内建函数


4.6.1 type()

>>> type('hello world')
<type 'str'>

4.6.2 com()


用来比较的内建函数

4.6.3 str() 和 repr()

>>> repr([0,5,9,9])
'[0, 5, 9, 9]'


4.6.4 type() 和 isinstance()


4.7 类型工厂函数


第 5 章 数字


5.1 数字类型

5.2 整型

5.3 双精度浮点数

5.5 运算符

5.5.2 标准类型运算符


5.6 内建函数与工厂函数

5.6.1 标准类型函数


>>> cmp(-6, 2)
-1

5.6.2 数字类型函数


转换工厂函数


>>> int(4.25555)
4


功能函数

abs() 返回给参数一个绝对值

>>> abs(-1)
1

divmod()


>>> divmod(10,3)
(3, 1)


pow(2,5)


>>> pow(2,5)
32

5.6 数值运算内建函数

5.6.3 仅用于整数的函数


进制转换函数


>>> hex(255)
'0xff'

ASCII转换函数


>>> ord('a')
97


其他数字类型


5.7.1 布尔“数”

第 6 章 序列 字符串、列表和元组


6.4 只适用于字符串的操作符

6.4.1 格式化操作附(%)

十六进制输出:

>>> "%x" % 108
'6c'

整数和字符输出

>>> "%+d" % -4
'-4'

>>> "we are at %d%%" % 100
'we are at 100%'


6.5.2 序列类型函数


>>> str1 = 'abc'
>>> len(str1)
3

6.5.3 字符串类型函数

6.6 字符串内建函数


6.7.3 字符串不变性

>>> 'abc' + 'def'
'abcdef'


6.8.5 编码解码

Unicode 支持多种编码格式,encoding 参数)用于把对应的 Unicode 内容转换成你定义的格
式,

6.8.8 Python 的 Unicode 支持

内建的 decode()/encode()方法

6.12 操作符
6.12.1 标准类型操作符


6.12.3 列表类型操作符和列表解析

>>> [ i * 2 for i in [8, -2, 5] ]
[16, -4, 10]
>>> [ i for i in range(8) if i % 2 == 0 ]
[0, 2, 4, 6]

6.13 内建函数

6.13.1 标准类型函数
cmp()

>>> list1, list2 = [123, 'xyz'], [456, 'abc']
>>> cmp(list1, list2)
-1
>>>
>>> cmp(list2, list1)
1
>>> list3 = list2 + [789]
>>> list3
[456, 'abc', 789]
>>>
>>> cmp(list2, list3)
-1


6.13.2 序列类型函数
len()

>>> len(num_list)
4

list() and tuple()

>>> aList = ['tao', 93, 99, 'time']
>>> aTuple = tuple(aList)
>>> aList, aTuple
(['tao', 93, 99, 'time'], ('tao', 93, 99, 'time'))

6.14 列表类型的内建函数

>>> music_media
[45]
>>> music_media.insert(0, 'compact disc')
>>> music_media
['compact disc', 45]
>>> music_media.append('long plaring record')
>>> music_media
['compact disc', 45, 'long plaring record']
>>>


6.15 列表的特殊性

6.15.1 用列表构建其他数据结果


6.17 元组操作符和内建函数

6.18


2 元组也不是那么“不可变”


>>> s = 'first'
>>> s =s + 'second'
>>> s
'firstsecond'

6.18.3 单元素元组

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


6.20 拷贝python对象浅深和深拷贝

>>> person = ['name', ['savings', 100.00]]
>>> hubby = person[:] # slice copy
>>> wifey = list(person) # fac func copy
>>> [id(x) for x in person, hubby, wifey]
[11826320, 12223552, 11850936]

>>> hubby[0] = 'joe'
>>> wifey[0] = 'jane'
>>> hubby, wifey
(['joe', ['savings', 100.0]], ['jane', ['savings', 100.0]])
>>> hubby[1][1] = 50.00
>>> hubby, wifey
(['joe', ['savings', 50.0]], ['jane', ['savings', 50.0]])

>>> person = ['name', ['savings', 100.00]]
>>> hubby = person
>>> import copy
>>> wifey = copy.deepcopy(person)
>>> [id(x) for x in person, hubby, wifey]
[12242056, 12242056, 12224232]
>>> hubby[0] = 'joe'
>>> wifey[0] = 'jane'
>>> hubby, wifey
(['joe', ['savings', 100.0]], ['jane', ['savings', 100.0]])
>>> hubby[1][1] = 50.00
>>> hubby, wifey
(['joe', ['savings', 50.0]], ['jane', ['savings', 100.0]])

>>> [id(x) for x in hubby]
[12191712, 11826280]

>>> [id(x) for x in wifey]
[12114080, 12224792]

>>> person = ['name', ('savings', 100.00)]
>>> newPerson = copy.deepcopy(person)
>>> [id(x) for x in person, newPerson]
[12225352, 12226112]
>>> [id(x) for x in person]
[9919616, 11800088]
>>> [id(x) for x in newPerson]
[9919616, 11800088]


映射和集合类型

7.1 字典

如何创建字典和给字典赋值

>>> dict1 = {}
>>> dict2 = {'name': 'earth', 'port': 80}
>>> dict1, dict2
({}, {'port': 80, 'name': 'earth'})


>>> fdict = dict((['x', 1], ['y', 2]))
>>> fdict
{'y': 2, 'x': 1}

>>> ddict = {}.fromkeys(('x', 'y'), -1)
>>> ddict
{'y': -1, 'x': -1}

>>> edict = {}.fromkeys(('foo', 'bar'))
>>> edict
{'foo': None, 'bar': None}


如何访问字典中的值

>>> dict2 = {'name': 'earth', 'port': 80}
>>>
>>>> for key in dict2.keys():
... print 'key=%s, value=%s' % (key, dict2[key])
...
key=name, value=earth
key=port, value=80

>>> dict2 = {'name': 'earth', 'port': 80}
>>>
>>>> for key in dict2:
... print 'key=%s, value=%s' % (key, dict2[key])
...
key=name, value=earth
key=port, value=80

>>> dict2['name']
'earth'
>>>
>>> print 'host %s is running on port %d' % \
... (dict2['name'], dict2['port'])
host earth is running on port 80


一个字典中混用数字和字符串的例子

>>> dict3 = {}
>>> dict3[1] = 'abc'
>>> dict3['1'] = 3.14159
>>> dict3[3.2] = 'xyz'
>>> dict3
{3.2: 'xyz', 1: 'abc', '1': 3.14159}


给 dict3 整体赋值

dict3 = {3.2: 'xyz', 1: 'abc', '1': 3.14159}

如何更新字典

如何删除字典元素和字典


del dict2['name'] # 删除键为“name”的条目
dict2.clear() # 删除 dict2 中所有的条目
del dict2 # 删除整个 dict2 字典
dict2.pop('name') # 删除并返回键为“name”的条目


7.2 映射类型操作符

7.2.1 标准类型操作符

>>> dict4 = {'abc': 123}
>>> dict5 = {'abc': 456}
>>> dict6 = {'abc': 123, 98.6: 37}
>>> dict7 = {'xyz': 123}
>>> dict4 < dict5
True
>>> (dict4 < dict6) and (dict4 < dict7)
True
>>> (dict5 < dict6) and (dict5 < dict7)
True
>>> dict6 < dict7
False

7.2.2 映射类型操作符


(键)成员关系操作( in ,not in)


>>> 'name' in dict2
True
>>> 'phone' in dict2
False


7.3 映射类型的内建函数和工厂函数


7.3.1 标准类型函数[type()、str()和 cmp()]

接下来的小节里,将进一步详细说明字典比较的算法,但这部分是高层次的阅读内容,可以跳
过,因为字典的比较不是很有用也不常见。
*字典比较算法

7.3.2 映射类型相关的函数


>> dict(zip(('x', 'y'), (1, 2)))
{'y': 2, 'x': 1}
>>> dict([['x', 1], ['y', 2]])
{'y': 2, 'x': 1}
>>> dict([('xy'[i-1], i) for i in range(1,3)])
{'y': 2, 'x': 1}


但是从已存在的字典生成新的字典速度比用 copy()方法慢,我们推荐使用 copy()

>>> dict9 = dict8.copy()
>>> dict9
{'y': 2, 'x': 1}

len()


>>> dict2 = {'name': 'earth', 'port': 80}
>>> dict2
{'port': 80, 'name': 'earth'}
>>> len(dict2)
2

hash()


如果非可哈希类型作为参数传递给 hash()方法,会产生 TypeError 错误(因此,如果使用这样的
对象作为键给字典赋值时会出错):


>>> hash([])
Traceback (innermost last): File "<stdin>", line 1, in ?
TypeError: list objects are unhashable
>>>
>>> dict2[{}] = 'foo'
Traceback (most recent call last): File "<stdin>", line 1, in ?
TypeError: dict objects are unhashable


表 7.1 映射类型的相关函数


dict([container])
len(mapping)
hash(obj)


7.4 映射类型内建方法

>>> dict2.keys()
['port', 'name']
>>>
>>> dict2.values()
[80, 'earth']
>>>
>>> dict2.items()
[('port', 80), ('name', 'earth')]
>>>
>>> for eachKey in dict2.keys():
... print 'dict2 key', eachKey, 'has value', dict2[eachKey]
...
dict2 key port has value 80
dict2 key name has value earth

我们通常希望它们能按某种
方式排序。

>>> for eachKey in sorted(dict2):
... print 'dict2 key', eachKey, 'has value',
dict2[eachKey]
...
dict2 key name has value earth
dict2 key port has value 80


update()方法可以用来将一个字典的内容添加到另外一个字典中


>>> dict2= {'host':'earth', 'port':80}
>>> dict3= {'host':'venus', 'server':'http'}
>>> dict2.update(dict3)
>>> dict2
{'server': 'http', 'port': 80, 'host': 'venus'}
>>> dict3.clear()
>>> dict3
{}


>>> dict4 = dict2.copy()
>>> dict4
{'server': 'http', 'port': 80, 'host': 'venus'}
>>> dict4.get('host')
'venus'
>>> dict4.get('xxx')
>>> type(dict4.get('xxx'))
<type 'None'>
>>> dict4.get('xxx', 'no such key')
'no such key'


setdefault()是自 2.0 才有的内建方法


>>> myDict = {'host': 'earth', 'port': 80}
>>> myDict.keys()
['host', 'port']
>>> myDict.items()
[('host', 'earth'), ('port', 80)]
>>> myDict.setdefault('port', 8080)
80
>>> myDict.setdefault('prot', 'tcp')
'tcp'
>>> myDict.items()
[('prot', 'tcp'), ('host', 'earth'), ('port', 80)]

前面,我们曾简要介绍过 fromkeys()方法,下面是更多的示例

>>> {}.fromkeys('xyz')
{'y': None, 'x': None, 'z': None}
>>>
>>> {}.fromkeys(('love', 'honor'), True)
{'love': True, 'honor': True}


7.5.1 不允许一个键对应多个值


>>> dict1 = {' foo':789, 'foo': 'xyz'}
>>> dict1
{'foo': 'xyz'}
>>>
>>> dict1['foo'] = 123
>>> dict1
{'foo': 123}


7.5.2 键必须是可哈希的


打造登陆系统 无法运行


1 #!/usr/bin/env python
3 db = {}
5 def newuser():
6 prompt = 'login desired: '
7 while True:
8 name = raw_input(prompt)
9 if db.has_key(name):
10 prompt = 'name taken, try another: '
11 continue
12 else:
13 break
14 pwd = raw_input('passwd: ')
15 db[name] = pwd
16
17 def olduser():
18 name = raw_input('login: ')
19 pwd = raw_input('passwd: ')
20 passwd = db.get(name)
21 if passwd == pwd:
22 print 'welcome back', name
23 else:
24 print 'login incorrect'
25
26 def showmenu():
27 prompt = """
28 (N)ew User Login
29 (E)xisting User Login
30 (Q)uit
Example 7.1 Dictionary Example (userpw.py) (continued)
31
32 Enter choice: """
33
34 done = False
35 while not done:
36
37 chosen = False
38 while not chosen:
39 try:
40 choice = raw_input(prompt).strip()[0].lower()
41 except (EOFError, KeyboardInterrupt):
42 choice = 'q'
43 print '\nYou picked: [%s]' % choice
44 if choice not in 'neq':
45 print 'invalid option, try again'
46 else:
47 chosen = True
49 done = True
50 newuser()
51 olduser()
52
53 if __name__ == '__main__':
54 showmenu()

7.6 集合类型

如何创建集合类型和给集合赋值

>>> s = set('cheeseshop')
>>> s
set(['c', 'e', 'h', 'o', 'p', 's'])
>>> t = frozenset('bookshop')
>>> t
frozenset(['b', 'h', 'k', 'o', 'p', 's'])
>>> type(s)
<type 'set'>
>>> type(t)
<type 'frozenset'>
>>> len(s)
6
>>> len(s) == len(t)
True
>>> s == t
False


如何访问集合中的值


>>> 'k' in s
False
>>> 'k' in t
True
>>> 'c' not in t
True
>>> for i in s:
... print i
...
c
e
h
o
p
s


如何更新集合


>>> s = set('cheeseshop')
>>> s.add('z')
>>> s
set(['c', 'e', 'h', 'o', 'p', 's', 'z'])


>>> s.update('pypi')
>>> s
set(['c', 'e', 'i', 'h', 'o', 'p', 's', 'y', 'z'])


>>> s.remove('z')
>>> s
set(['c', 'e', 'i', 'h', 'o', 'p', 's', 'y'])

如何删除集合中的成员和集合


>>> del s

7.7 集合类型操作符


7.7.1 标准类型操作符(所有的集合类型)

>>> s = set('cheeseshop')
>>> t = frozenset('bookshop')
>>> 'k' in s
False
>>> 'k' in t
True
>>> 'c' not in t
True


集合等价/不等价


>>> u = frozenset(s)
>>> s == u
True
>>> set('posh') == set('shop')
True


子集/超集


>>> set('shop') < set('cheeseshop')
True
>>> set('bookshop') >= set('shop')
True

7.7.2 集合类型操作符(所有的集合类型)

联合( | )

>>> s | t
set(['c', 'b', 'e', 'h', 'k', 'o', 'p', 's'])

交集( & )

>>> s & t
set(['h', 's', 'o', 'p']

差补/相对补集( – )

>>> s - t
set(['c', 'e'])


对称差分( ^ )


>>> s ^ t
set(['k', 'b', 'e', 'c'])


混合集合类型操作


左边的 s 是可变集合,而右边的 t 是一个不可变集合. 注意上面使用集合操作
运算符所产生的仍然是可变集合,但是如果左右操作数的顺序反过来,结果就不一样了:
>>> t | s
frozenset(['c', 'b', 'e', 'h', 'k', 'o', 'p', 's'])
>>> t ^ s
frozenset(['c', 'b', 'e', 'k'])
>>> t - s frozenset(['k', 'b'])


>>> v = s + t
Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: unsupported operand type(s) for +: 'set' and 'set'
>>> v = s | t
>>> v
set(['c', 'b', 'e', 'h', 'k', 'o', 'p', 's'])
>>> len(v)
8
>>> s < v
True

7.7.3 集合类型操作符(仅适用于可变集合)

(Union) Update ( |= )

>>> s = set('cheeseshop')
>>> u = frozenset(s)
>>> s |= set('pypi')
>>> s
set(['c', 'e', 'i', 'h', 'o', 'p', 's', 'y'])

保留/交集更新( &= )

>>> s = set(u)
>>> s &= set('shop')
>>> s
set(['h', 's', 'o', 'p'])

差更新 ( –= )

>>> s = set(u)
>>> s -= set('shop')
>>> s
set(['c', 'e'])

对称差分更新( ^= )

>>> s = set(u)
>>> t = frozenset('bookshop')
>>> s ^= t
>>> s
set(['c', 'b', 'e', 'k'])


7.8 内建函数


7.8.1 标准类型函数


len()
>>> s = set(u)
>>> s
set(['p', 'c', 'e', 'h', 's', 'o'])
>>> len(s)
6

7.8.2 集合类型工厂函数


set() and frozenset()

>>> set()
set([])
>>> set([])
set([])
>>> set(())
set([])
>>> set('shop')
set(['h', 's', 'o', 'p'])
>>>
>>> frozenset(['foo', 'bar'])
frozenset(['foo', 'bar'])
>>>
>>> f = open('numbers', 'w')
>>> for i in range(5):
... f.write('%d\n' % i)
...
>>> f.close()
>>> f = open('numbers', 'r')
>>> set(f)
set(['0\n', '3\n', '1\n', '4\n', '2\n'])
>>> f.close()

7.9 集合类型内建方法


7.9.1 方法(所有的集合方法)

s.issubset(t) 如果 s 是 t 的子集,则返回 True,否则返回 False
s.issuperset(t) 如果 t 是 s 的超集,则返回 True,否则返回 False
s.union(t) 返回一个新集合,该集合是 s 和 t 的并集
s.intersection(t) 返回一个新集合,该集合是 s 和 t 的交集
Edit?By?Vheavens
Edit?By?Vheavens
s.difference(t) 返回一个新集合,该集合是 s 的成员,但不是 t 的成员
s.symmetric_difference(t) 返回一个新集合,该集合是 s 或 t 的成员,但不是 s 和 t 共有的
成员
s.copy() 返回一个新集合,它是集合 s 的浅复制

7.9.2 方法(仅适用于可变集合)


新的方法有 add(), remove(), discard(), pop(), clear(). 这些接受对象的方法,参数必
须是可哈希的。

7.9.3 操作符和内建方法比较


7.10 操作符、函数/方法

7.11 相关模块

条件和循环


本章主题
本章主题
? if 语句
? else 语句
? elif 语句
? 条件表达式
? while 语句
? for 语句
? break 语句
? continue 语句
? pass 语句
? else 语句 (再看)
? Iterators 迭代器
? 列表解析(List Comprehensions)
? 生成器表达式(Generator Expressions )


8.1 if 语句


8.1.1 多重条件表达式


8.1.2 单一语句的代码块


8.2 else 语句


8.3 elif (即 else-if )语句

8.4 条件表达式(即"三元操作符")


x, y = 4, 3
if x < y:
smaller = x
else:
smaller = y
smaller
print smaller

3

8.5 while 语句

8.5.1 一般语法

8.5.2 计数循环


count = 0
while (count < 9):
print 'the index is:', count
count += 1

the index is: 0
the index is: 1
the index is: 2
the index is: 3
the
the index is: 4
the index is: 5
the index is: 6
the index is: 7
the index

8.5.3 无限循环

8.6 for 语句


8.6.1 一般语法


8.6.2 用于序列类型

>>> for eachLetter in 'Names':
... print 'current letter:', eachLetter
...
current letter: N
current letter: a
current letter: m
current letter: e
current letter: s


通过序列项迭代


>>> nameList = ['Walter', "Nicole", 'Steven', 'Henry']
>>> for eachName in nameList:
... print eachName, "Lim"
...
Walter Lim
Nicole Lim
Steven Lim
Henry Lim


===通过序列索引迭代===

>>> nameList = ['Cathy', "Terry", 'Joe', 'Heather',
'Lucy']
>>> for nameIndex in range(len(nameList)):
... print "Liu,", nameList[nameIndex]
...
Liu, Cathy
Liu, Terry
Liu, Joe
Liu, Heather
Liu, Lucy

>>> len(nameList)
5
>>> range(len(nameList))


===使用项和索引迭代===

>>> nameList = ['Donn', 'Shirley', 'Ben', 'Janice',
... 'David', 'Yen', 'Wendy']
>>> for i, eachLee in enumerate(nameList):
... print "%d %s Lee" % (i+1, eachLee)
...
1 Donn Lee
2 Shirley Lee
3 Ben Lee
4 Janice Lee
5 David Lee
6 Yen Lee
7 Wendy Lee

8.6.3 用于迭代器类型


8.6.4 range() 内建函数

=== range() 的完整语法===


range(start, end, step =1)


>>> range(2, 19, 3)
[2, 5, 8, 11, 14, 17]


如果只给定两个参数,而省略 step, step 就使用默认值 1

>>> range(3, 7)
[3, 4, 5, 6]


>>> for eachVal in range(2, 19, 3):
... print "value is:", eachVal
...
value is: 2
value is: 5
value is: 8
value is: 11
value is: 14
value is: 17

===range() 简略语法===
range() 还有两种简略的语法格式:
range(end)
range(start, end)


>>> for count in range(2, 5):
... print count
...
2
3
4


8.6.5 xrange() 内建函数


8.6.6 与序列相关的内建函数


sorted(), reversed(), enumerate(), zip()

>>> albums = ('Poe', 'Gaudi', 'Freud', 'Poe2')
>>> years = (1976, 1987, 1990, 2003)
>>> for album in sorted(albums):
... print album,
...
Freud Gaudi Poe Poe2
>>>
>>> for album in reversed(albums):
... print album,
...
Poe2 Freud Gaudi Poe
>>>
>>> for i, album in enumerate(albums):
... print i, album
...
0 Poe
1 Gaudi
2 Freud
3 Poe2
>>>
>>> for album, yr in zip(albums, years):
... print yr, album
...
Edit?By?Vheavens
Edit?By?Vheavens
1976 Poe
1987 Gaudi
1990 Freud
2003 Poe2

8.7 break 语句

8.8 continue 语句


8.9 pass 语句


8.10 再谈 else 语句

8.11 迭代器和 iter() 函数

8.11.4 使用迭代器
===序列===


>>> myTuple = (123, 'xyz', 45.67)
>>> i = iter(myTuple)
>>> i.next()
123
>>> i.next()
'xyz'
>>> i.next()
45.67
>>> i.next()
Traceback (most recent call last):
File "", line 1, in ?
StopIteration


===字典===


>>> myFile = open('config-win.txt')
>>> for eachLine in myFile:
... print eachLine, # comma suppresses extra \n
...
[EditorWindow]
font-name: courier new
font-size: 10
>>> myFile.close()


8.11.5 可变对象和迭代器


8.11.6 如何创建迭代器

iter(obj)
iter(func, sentinel )

8.12 列表解析


>>> map(lambda x: x ** 2, range(6))
[0, 1, 4, 9, 16, 25]


>>> [x ** 2 for x in range(6)]
[0, 1, 4, 9, 16, 25]


回想下 odd() 函数, 它用于判断一个数值对象是奇数还是偶数(奇数返回 1 , 偶数返回 0 ):
def odd(n):
return n % 2

我们可以借用这个函数的核心操作, 使用 filter() 和 lambda 挑选出序列中的奇数:

>>> seq = [11, 10, 9, 9, 10, 10, 9, 8, 23, 9, 7, 18, 12, 11, 12]
>>> filter(lambda x: x % 2, seq)
[11, 9, 9, 9, 23, 9, 7, 11]

>>> [x for x in seq if x % 2]
[11, 9, 9, 9, 23, 9, 7, 11]

===矩阵样例===
你需要迭代一个有三行五列的矩阵么? 很简单:
>>> [(x+1,y+1) for x in range(3) for y in range(5)]
[(1, 1), (1, 2), (1, 3), (1, 4), (1, 5), (2, 1), (2, 2), (2,
3), (2, 4), (2, 5), (3, 1), (3, 2), (3, 3), (3, 4), (3, 5)]


8.13 生成器表达式

它与列表解析非常相似,


列表解析:
[expr for iter_var in iterable if cond_expr]
生成器表达式:
(expr for iter_var in iterable if cond_expr)


===磁盘文件样例===


=== 交叉配对例子 ===


不需要创建新的列表, 直接就可以创建配对. 我们可以使用下面的生成器表达式:

x_product_pairs = ((i, j) for i in rows for j in cols())

=== 重构样例 ===

文件和输入输出


本章主题
本章主题
? 文件对象
? 文件内建函数
? 文件内建方法
? 文件内建属性
? 标准文件
? 命令行参数
? 文件系统
? 文件执行
? 持久存储
?

9.1 文件对象

9.2 文件内建函数[open()和 file()]


表 9.1 文件对象的访问模式
文件模式 操作
r 以读方式打开

rU 或 Ua 以读方式打开, 同时提供通用换行符支持 (PEP 278)
w 以写方式打开 (必要时清空)
a 以追加模式打开 (从 EOF 开始, 必要时创建新文件)
r+ 以读写模式打开
w+ 以读写模式打开 (参见 w )
a+ 以读写模式打开 (参见 a )
rb 以二进制读模式打开
wb 以二进制写模式打开 (参见 w )
ab 以二进制追加模式打开 (参见 a )
rb+ 以二进制读写模式打开 (参见 r+ )
wb+ 以二进制读写模式打开 (参见 w+ )
ab+ 以二进制读写模式打开 (参见 a+ )


这里是一些打开文件的例子:
fp = open('/etc/motd') # 以读方式打开
fp = open('test', 'w') # 以写方式打开
fp = open('data', 'r+') # 以读写方式打开
fp = open(r'c:\io.sys', 'rb') # 以二进制读模式打开

9.2.1 工厂函数 file()

9.2.2 通用换行符支持(UNS)

9.3 文件内建方法

9.3.1 输入

9.3.2 输出


9.3.3 文件内移动

9.3.3 文件迭代


9.3.5 其它

9.4 文件内建属性

错误和异常


10.3 检测和处理异常

异常可以通过 try 语句来检测. 任何在 try 语句块里的代码都会被监测, 检查有无异常发
生.

ry-except 和 try-finally . 这两个语句是互斥的, 也就是说你
只能使用其中的一种.


ry:
try_suite # watch for exceptions here 监控这里的异常
except Exception[, reason]:
except_suite # exception-handling code 异常处理代码

>>> try:
... f = open('blah', 'r')
... except IOError, e:
... print 'could not open file:', e
...
could not open file: [Errno 2] No such file or directory


10.3.2 封装内建函数


>>> float(12345)
12345.0

10.3.3 带有多个 except 的 try 语句

10.3.4 处理多个异常的 except 语句

10.3.5 捕获所有异常

10.3.6 异常参数


10.3.8 else 子句

import 3rd_party_module
Edit?By?Vheavens
Edit?By?Vheavens
log = open('logfile.txt', 'w')
try:
3rd_party_module.function()
except:
log.write("*** caught exception in module\n")
else:
log.write("*** no exceptions caught\n")
log.close()


10.3.9 finally 子句


下面是 try-except-else-finally 语法的示例:
try:
A
except MyException: B
else: C
finally: D
等价于 Python 0.9.6 至 2.4.x 中如下的写法:
try:
try:
A
Edit?By?Vheavens
Edit?By?Vheavens
except MyException:
B
else: C
finally:
D

10.3.10 try-finally 语句

try:
try_suite
finally:
finally_suite #无论如何都执行

ccfile = None
try:
try:
ccfile = open('carddata.txt', 'r')
txns = ccfile.readlines()
except IOError:
log.write('no txns this month\n')
finally:
if ccfile:
ccfile.close()



代码片段会尝试打开文件并且读取数据.如果在其中的某步发生一个错误,会写入日志,随后文
件被正确的关闭.如果没有错误发生,文件也会被关闭.

10.3.11 try-except-else-finally:厨房一锅端


10.4 上下文管理
10.4.1 with 语句

10.4.2 *上下文管理协议


10.5 *字符串作为异常

10.6 触发异常

10.6.1 raise 语句

raise [SomeException [, args [, traceback]]]


10.7.1 断言语句


>>> assert 1 == 0
Traceback (innermost last): File "<stdin>", line 1, in ?
AssertionError


10.8 标准异常


异常名称 描述
BaseException
a 所有异常的基类
SystemExit
b python 解释器请求退出
KeyboardInterrupt
c 用户中断执行(通常是输入^C)
Exception
d 常规错误的基类
StopIteration
e 迭代器没有更多的值
GeneratorExit
a 生成器(generator)发生异常来通知退出
SystemExit
h Python 解释器请求退出
StandardError
g 所有的内建标准异常的基类
ArithmeticError
d 所有数值计算错误的基类
FloatingPointError
d 浮点计算错误
OverflowError 数值运算超出最大限制
ZeroDivisionError 除(或取模)零 (所有数据类型)
AssertionError
d 断言语句失败
AttributeError 对象没有这个属性
EOFError 没有内建输入,到达 EOF 标记
EnvironmentError
d 操作系统错误的基类
IOError 输入/输出操作失败
OSError
d 操作系统错误
WindowsError
h Windows 系统调用失败
ImportError 导入模块/对象失败
KeyboardInterrupt
f 用户中断执行(通常是输入^C)
LookupError
d 无效数据查询的基类
IndexError 序列中没有没有此索引(index)
KeyError 映射中没有这个键
MemoryError 内存溢出错误(对于 Python 解释器不是致命的)
NameError 未声明/初始化对象 (没有属性)
UnboundLocalErrorh 访问未初始化的本地变量
ReferenceError
e 弱引用(Weak reference)试图访问已经垃圾回收了的对象
RuntimeError 一般的运行时错误
NotImplementedError
d 尚未实现的方法
SyntaxError Python 语法错误
IndentationError
g 缩进错误
TabError
g Tab 和空格混用
SystemError 一般的解释器系统错误
TypeError 对类型无效的操作
ValueError 传入无效的参数
UnicodeError
h Unicode 相关的错误
UnicodeDecodeError
i Unicode 解码时的错误
UnicodeEncodeError
i Unicode 编码时错误
Edit?By?Vheavens
Edit?By?Vheavens
UnicodeTranslateError
f Unicode 转换时错误
Warning
j 警告的基类
DeprecationWarning
j 关于被弃用的特征的警告
FutureWarning
i 关于构造将来语义会有改变的警告
OverflowWarning
k 旧的关于自动提升为长整型(long)的警告
PendingDeprecationWarning
i 关于特性将会被废弃的警告
RuntimeWarning
j 可疑的运行时行为(runtime behavior)的警告
SyntaxWarning
j 可疑的语法的警告
UserWarning
j 用户代码生成的警告

10.9 *创建异常

10.11 到底为什么要异常?


10.12 异常和 sys 模块

10.13 相关模块


函数和函数式编程

章节主题
? 什么是函数
? 调用函数
? 创建函数
? 传入函数
? 形参
? 变长参数
? 函数式编程
? 变量的作用域
? 递归
?

11.1.1 函数 vs 过程
11.1.2.返回值与函数类型

11.2 调用函数
11.2.1.函数操作符

11.2.2.关键字参数


11.2.3.默认参数


11.2.4.参数组


11.3 创建函数
11.3.1. def 语句

11.3.2.声明与定义比较


11.3.3 前向引用

11.7 函数式编程


11.7.1.匿名函数与 lambda

11.7.2 内建函数 apply()、filter()、map()、reduce()

map()


reduce()


11.7.3 偏函数应用


>>> from operator import add, mul
>>> from functools import partial
>>> add1 = partial(add, 1) # add1(x) == add(1, x)
>>> mul100 = partial(mul, 100) # mul100(x) == mul(100, x)
>>>
>>> add1(10)
11
>>> add1(1)
2
>>> mul100(10)
1000
>>> mul100(500)
50000


警惕关键字

11.8 变量作用域


11.8.1 全局变量与局部变量

11.8.2. globa 语句


11.8.5 作用域和 lambda

11.8.6 变量作用域和名字空间。


11.9 *递归

11.10 生成器

11.10.1.简单的生成器特性

模块


本章主题
? 什么是模块?
? 模块和文件
? 命名空间
? 导入模块
? 导入模块属性
? 模块内建函数包
? 模块的其他特性

12.3.1 名称空间与变量作用域比较


12.4.2 from-import 语句

12.4.3 多行导入


12.4.4 扩展的 import 语句(as)


12.5 模块导入的特性
12.5.1 载入时执行模块

12.5.2 导入(import )和加载(load)

12.5.3 导入到当前名称空间的名称

12.5.4 被导入到导入者作用域的名字


12.5.5 关于 __future__


12.5.6 警告框架


12.5.7 从 ZIP 文件中导入模块

12.5.8 "新的"导入钩子

12.6 模块内建函数


12.6.1 __import__()


12.6.2 globals() 和 locals()

12.6.3 reload()

12.7.1 目录结构


12.7.2 使用 from-import 导入包

12.7.3 绝对导入

12.7.4 相对导入

12.8 模块的其他特性
12.8.1 自动载入的模块

12.8.2 阻止属性导入


12.8.3 不区分大小的导入

12.8.4 源代码编码

12.8.5 导入循环

12.8.5 模块执行

12.9 相关模块


面向对象编程

本章主题
? 引言
? 面向对象编程
? 类
? 实例
? 绑定与方法调用
? 子类,派生和继承
? 内建函数
? 定制类
? 私有性
? 授权与包装
? 新式类的高级特性
?

13.1 介绍


类与实例


创建实例(实例化)

>>> john = AddrBookEntry('John Doe', '408-555-1212') #为 John Doe 创建实例
>>> jane = AddrBookEntry('Jane Doe', '650-555-1212') #为 Jane Doe 创建实例


访问实例属性


方法调用(通过实例)

创建子类

使用子类


13.2 面向对象编程


13.2.1 面向对象设计与面向对象编程的关系


13.3 类

13.3.1 创建类


13.3.2 声明与定义

13.4 类属性


13.4.1 类的数据属性

13.4.2 方法

绑定(绑定及非绑定方法)


13.4.2 决定类的属性

13.4.3 特殊的类属性


13.5.1 初始化:通过调用类对象来创建实例

13.5.2 __init__() "构造器"方法


13.5.3 __new__() “构造器”方法

13.5.4 __del__() "解构器"方法


13.6 实例属性

13.6.1 “实例化”实例属性(或创建一个更好的构造器


13.6.2 查看实例属性


>>> class C(object):
... pass
>>> c = C()
>>> c.foo = 'roger'
>>> c.bar = 'shrubber'
>>> dir(c)
['__class__', '__delattr__', '__dict__', '__doc__',
'__getattribute__', '__hash__', '__init__', '__module__',
'__new__', '__reduce__', '__reduce_ex__', '__repr__',
'__setattr__', '__str__', '__weakref__', 'bar', 'foo']

>>> c.__dict__
{'foo': 'roger', 'bar': 'shrubber'}


13.6.3 特殊的实例属性

>>> class C(object): # define class 定义类
... pass
...
>>> c = C() # create instance 创建实例
>>> dir(c) # instance has no attributes 实例还没有属性
[]
>>> c.__dict__ # yep, definitely no attributes 也没有属性
{}
>>> c.__class__ # class that instantiated us 实例化 c 的类
<class '__main__.C'>
你可以看到,c 现在还没有数据属性,但我们可以添加一些再来检查__dict__属性,看是否添加
成功了:
>>> c.foo = 1
>>> c.bar = 'SPAM'
>>> '%d can of %s please' % (c.foo, c.bar)
'1 can of SPAM please'
>>> c.__dict__
{'foo': 1, 'bar': 'SPAM'}

13.6.4 内建类型属性


13.6.5 实例属性 vs 类属性

访问类属性

>> class C(object): # define class 定义类
... version = 1.2 # static member 静态成员
...
>>> c = C() # instantiation 实例化
>>> C.version # access via class 通过类来访问
1.2
>>> c.version # access via instance 通过实例来访问
1.2
>>> C.version += 0.1 # update (only) via class 通过类(只能这样)来更新
>>> C.version # class access 类访问
1.3
>>> c.version # instance access, which 实例访问它,其值已被改变
1.3 # also reflected change


从实例中访问类属性须谨慎

13.8.1 staticmethod()和 classmethod()内建函数

13.11.1 __bases__类属性

13.11.2 通过继承覆盖(Overriding)方法

13.12 类、实例和其他对象的内建函数
13.12.1 issubclass()

13.12.2 isinstance()


13.12.3 hasattr(), getattr(),setattr(), delattr()

13.12.4 dir()

13.12.5 super()

13.12.6 vars()


13.13 用特殊方法定制类


13.13.1 简单定制(RoundFloat2)

13.13.2 数值定制(Time60)

13.13.3 迭代器(RandSeq 和 AnyIter)


AnyIter


13.13.4 *多类型定制(NumStr)

13.14 私有化

13.15.2 实现授权
包装对象的简例


更新简单的包裹类

13.16 新式类的高级特性 (Python 2.2+)
13.16.1 新式类的通用特性

13.16.2 __slots__类属性

13.16.3 特殊方法__getattribute__()


13.16.4 描述符
__get__(),__set__(),__delete__()特殊方法


__getattribute__() 特殊方法(二)

描述符举例

13.16.5 Metaclasses 和__metaclass__


执行环境


本章主题
本章主题
? 可调用对象
? 代码对象
? 语句和内置函数
? 执行其他程序
? 终止执行
? 各类操作系统接口
?

14.1 可调用对象


14.1.1 函数

14.1.2 方法


14.3 内建方法(BIM)属性

用户定义的方法(UDM)

14.1.3 类


14.1.4 类的实例

14.2 代码对象

14.3 可执行的对象声明和内建函数


14.3.1 callable()

14.3.2 compile()


可求值表达式
>>> eval_code = compile('100 + 200', '', 'eval')
>>> eval(eval_code)
300
单一可执行语句
>>> single_code = compile('print "Hello world!"', '', 'single')
>>> single_code
<code object ? at 120998, file "", line 0>
>>> exec single_code
Hello world!

可执行语句组


>>> exec_code = compile("""
... req = input('Count how many numbers? ')
... for eachNum in range(req):
... print eachNum
... """, '', 'exec')
>>> exec exec_code
Count how many numbers? 6
0
1
2
3
4
5


14.3.3 eval()

>>> eval('932')
932
>>> int('932')
932

14.3.4 exec


>>> exec """
... x = 0
... print 'x is currently:', x
... while x < 5:
... x += 1
... print 'incrementing x to:', x
... """
x is currently: 0
incrementing x to: 1
incrementing x to: 2
incrementing x to: 3
incrementing x to: 4
incrementing x to: 5

14.3 可执行对象语句和内建函数


14.3.5 input()


14.3.6 使用 Python 在运行时生成和执行 Python 代码


14.4 执行其他(Python)程序


14.4.2 execfile()

14.4.3 将模块作为脚本执行


14.5 执行其他(非 Python)程序


14.5.1 os.system()


14.5.2 os.popen()

14.5.3 os.fork(), os.exec*(),os.wait*()

14.5.4 os.spawn*()

14.5.5 subprocess 模块


14.7.1 sys.exit() and SystemExit


14.7.2 sys.exitfunc()


14.7.3 os._exit() Function os._exit() 函数


14.7.4 os.kill() Function


14.8 各种操作系统接口

14.9 相关模块


正则表达式


本章主题
? 引言/动机
? 特别的字符和符号
? 正则表达式与 Python
? re 模块
Edit?By?Vheavens

15.2.1 用管道符号( | )匹配多个正则表达式模式


15.2.2 匹配任意一个单个的字符( . )


15.2.4 从字符串的开头或结尾或单词边界开始匹配( ^/$ /\b /\B )


15.2.5 创建字符类( [ ] )


15.2.5 指定范围 ( - ) 和 否定( ^ )


15.2.6 使用闭包操作符 ( *, +, ?, {} ) 实现多次出现/重复匹配


15.2.7 特殊字符表示字符集


15.2.8 用圆括号(()) 组建组


15.3 正则表达式和 Python 语言

15.3.1 re 模块: 核心函数和方法

15.3.2 使用 compile()编译正则表达式


15.3.3 匹配对象 和 group(), groups() 方法

15.3.4 用 match()匹配字符串


15.3.5 search() 在一个字符串中查找一个模式 (搜索与匹配的比
较)

15.3.6 匹配多个字符串( | )


15.3.7 匹配任意单个字符( . )


15.3.8 创建字符集合( [ ] )


15.3.9 重复、特殊字符和子组

15.3.10 从字符串的开头或结尾匹配及在单词边界上的匹配


>>> m = re.match('ab', 'ab') # no subgroups #无子组
>>> m.group() # entire match
'ab'
>>> m.groups() # all subgroups #所有匹配的子组
()
>>>
>>> m = re.match('(ab)', 'ab') # one subgroup #一个子组
>>> m.group() # entire match #所有匹配
'ab'
>>> m.group(1) # subgroup 1 #匹配的子组 1
'ab'
>>> m.groups() # all subgroups


15.3.10 从字符串的开头或结尾匹配及在单词边界上的匹配


>>> m = re.search('^The', 'The end.') # match #匹配
>>> if m is not None: m.group()
...
'The'
>>> m = re.search('^The', 'end. The') # not at beginning #不在开头
>>> if m is not None: m.group()
...
>>> m = re.search(r'\bthe', 'bite the dog') # at a boundary #在词边界
>>> if m is not None: m.group()
...
'the'

15.3.11 用 findall()找到每个出现的匹配部分

>>> re.findall('car', 'car')
['car']
>>> re.findall('car', 'scary')
['car']
>>> re.findall('car', 'carry the barcardi to the car')
['car', 'car', 'car']


15.3.12 用 sub()[和 subn()]进行搜索和替换

>>> re.sub('X', 'Mr. Smith', 'attn: X\n\nDear X,\n')
'attn: Mr. Smith\012\012Dear Mr. Smith,\012'


15.3.13 用 split()分割(分隔模式


>>> re.split(':', 'str1:str2:str3')
['str1', 'str2', 'str3']

15.4.2 搜索与匹配的比较,“贪婪”匹配

>>> patt = '\d+-\d+-\d+'
>>> re.search(patt, data).group() # entire match #全部匹配部分
'1171590364-6-8'

网络编程


本章主题
? 引言:客户/服务器架构
? 套接字:通信终点
? 面向连接与无连接套接字
? Python 中的网络编程
? Socket 模块
? 套接字对象方法
? TCP/IP 客户端和服务器
? UDP/IP 客户端和服务器
? SocketServer 模块
? Twisted 框架介绍
?

16.2 套接字:通讯端点
16.2.1 什么是套接字?

16.2.2 套接字地址:主机与端口


16.2.3 面向连接与无连接

16.3 Python 中的网络编程

16.3.1 socket()模块函数

要使用 socket.socket()函数来创建套接字。其语法如下:
socket(socket_family, socket_type, protocol=0)

创建一个 TCP/IP 的套接字,你要这样调用 socket.socket():
tcpSock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)


16.3.2 套接字对象(内建)方法

16.3.3 创建一个 TCP 服务器


16.3.4 创建 TCP 客户端


16.3.5 运行我们的客户端与服务器程序

16.3.6 创建一个 UDP 服务器

16.3.8 执行 UDP 服务器和客户端


16.3.9 套接字模块属性

16.4 *SocketServer 模块

16.4.1 创建一个 SocketServerTCP 服务器

16.4.2 创建 SocketServerTCP 客户端

16.4.2 执行 TCP 服务器和客户端


16.5 Twisted 框架介绍

16.5.1 创建一个 Twisted Reactor TCP 服务器


16.5.2 创建一个 Twisted Reactor TCP 客户端


16.5.3 执行 TCP 服务器和客户端


16.6 相关模块


网络客户端编程


本章主题
本章主题
? 引言
? 文件传输
? 文件传输协议(FTP)
? 网络新闻、Usenet, 和新闻组
? 网络新闻传输协议(NNTP)
? 电子邮件
? 简单邮件传输协议(SMTP)
? 邮局协议 3(POP3)
?

17.2 文件传输
17.2.1 文件传输因特网协议
17.2 文件传输
17.2.1 文件传输因特网协议


17.2.2 文件传输协议(FTP)


17.2.3 Python 和 FTP

1. 连接到服务器
2. 登录
3. 发出服务请求 (有可能有返回信息)
4. 退出


17.2.4 ftplib.FTP 类方法


17.2.5 交互式 FTP 示例


17.2.6 客户端 FTP 程序举例


17.3 网络新闻
17.3.1 Usenet 与新闻组

17.3.2 网络新闻传输协议(NNTP)


17.3.3 Python 和 NNTP

17.3.4 nntplib.NNTP 类方法


17.3.5 交互式 NNTP 举例

17.3.6 客户端程序 NNTP 举例


17.4 电子邮件


17.4.1 E-mail 系统组件和协议

17.4.2 发送 E-mail

17.4.3 Python 和 SMTP


17.4.4 smtplib.SMTP 类方法

17.4.5 交互式 SMTP 示例


17.4.7 接收 E-mail

17.4.9 Python 和 POP3


17.4.10 交互式 POP3 举例


17.4.10 poplib.POP3 类方法


17.4.12 客户端程序 SMTP 和 POP3 举例

多线程编程

本章主题
本章主题
? 引言/动机
? 线程和进程
? 线程和 Python
? thread 模块
? threading 模块
? 生产者-消费者问题和 Queue 模块
?


18.3 Python、线程和全局解释器锁
18.3.1 全局解释器锁(GIL)


1. 设置 GIL
2. 切换到一个线程去运行
3. 运行:
a. 指定数量的字节码指令,或者
b. 线程主动让出控制(可以调用 time.sleep(0))
4. 把线程设置为睡眠状态
5. 解锁 GIL
6. 再次重复以上所有步骤

18.3.3 在 Python 中使用线程

18.3.5 Python 的 threading 模块


18.4 thread 模块


18.5 threading 模块


18.5.4 斐波那契,阶乘和累加和


18.5.5 threading 模块中的其它函数


18.5.5 生产者-消费者问题和 Queue 模块


图形用户界面编程

本章主题
? 引言
? Tkinter 与 Python 编程
? Tkinter 模块
? Tk 组件库
? Tkinter 使用举例
? 标签、按钮与进度条组件
? 一个使用 Tk 的中级范例
? 其他 GUI 简介(Tix, Pmw, wxPython, PyGTK)
?

19.1.1 什么是 Tcl、Tk 和 Tkinter?


19.1.2 安装和使用 Tkinter


19.1.3 客户端/服务器架构

19.2 Tkinter 与 Python 编程
19.2.1 Tkinter 模块:把 Tk 引入您的程序

19.2.2 GUI 程序开发简介

19.2.3 顶层窗口:Tkinter.Tk()


19.2.4 Tk 组件


#!/usr/bin/env python
import Tkinter
top = Tkinter.Tk()
label = Tkinter.Label(top, text='Hello World!')
label.pack()
Tkinter.mainloop()


19.3 Tkinter 举例
19.3.1 标签组件

19.3.2 按钮组件

19.3.3 标签和按钮组件


19.3.4 标签、按钮和进度条组件


19.3.5 偏函数应用举例

19.3.6 中级 Tkinter 范例


19.4 其他 GUI 简介

19.4.1 Tk Interface eXtensions (Tix)


19.4.2 Python MegaWidgets (PMW)


19.4.3 wxWidgets 和 wxPython


19.4.4 GTK+ 和 PyGTK


19.5 相关模块和其他 GUI

Web 编程


本章主题
本章主题
? 引言
? Python 的 Web 应用:简单的 Web 客户端
? urlparse 和 urllib 模块
? 高级的 Web 客户端
? 网络爬虫/蜘蛛/机器人
? CGI:帮助 Web 服务器处理客户端数据
? 创建 CGI 应用程序
? 在 CGI 中使用 Unicode
? 高级 CGI
? 创建 Web 服务器
?


20.1.1 Web 应用:客户端/服务器计算

20.1.2 因特网


20.2 使用 Python 进行 Web 应用:创建一个简单的 Web 客户端


20.2.1 统一资源定位符

20.2.3 urllib 模块


urllib.urlretrieve()


urllib.quote() and urllib.quote_plus()


urllib.unquote() 和 urllib.unquote_plus()


20.2.4 urllib2 模块


20.3 高级 Web 客户端


20.4 CGI:帮助 Web 服务器处理客户端数据

20.4.1 CGI 介绍

20.4.2 cgi 模块


20.5 建立 CGI 应用程序
20.5.1 建立 Web 服务器

20.5.2 建立表单页


20.5.3 生成结果页


20.5.4 生成表单和结果页面


20.5.5 全面交互的 Web 站点

20.6 在 CGI 中使用 Unicode 编码


20.7 高级 CGI


20.7.1 Mulitipart 表单提交和文件的上传

20.7.2 多值字段


20.7.3 cookie

20.7.4 使用高级 CGI


20.8 Web(HTTP)服务器

20.8.1 用 Python 建立 Web 服务器


20.9 相关模块


数据库编程


本章主题
? 介绍
? 数据库 和 Python RDBMSs, ORMs, and Python
? Python 数据库应用程序程序员接口(DB-API)
? 关系数据库 (RDBMSs)
? 对象-关系管理器(ORMs)
? 关系模块
? 练习


21.1 介绍
21.1.1 持久存储

21.1.2 基本的数据库操作和 SQL 语言


底层存储
数据库的底层存储通常使用文件系统, 它可以是普通操作系统文件、专用操作系统文件,甚至有
可能是磁盘分区。

21.1.3 数据库 和 Python

21.2 Python 数据库应用程序
程序员接口(DB-API)

21.2.1 模块属性

数据属性
apilevel

21.2.2 连接对象

表 21.5 连接对象方法
Method Name Description
close() 关闭数据库连接
commit() 提交当前事务
rollback() 取消当前事务
cursor() 使用这个连接创建并返回一个游标或类游标的对象
errorhandler (cxn, cur,
errcls, errval)

21.2.3 游标对象


21.2.4 类型对象和构造器

21.2.5 关系数据库

21.2.6 数据库和 Python:接口程序

21.2.7 使用数据库接口程序举例


MySQL


例子 21.1 数据库接口程序示例


21.3 对象-关系管理器(ORMs)

21.3.1 考虑对象,而不是 SQL


扩展 Python


本章主题
? 引言/动机
? 扩展 Python
? 创建应用程序代码
? 用样板包装你的代码
? 编译
? 导入并测试
? 引用计数
? 线程和 GIL
?

其它话题


本章主题
? 引言
? Web 服务
? 用 Win32 的 COM 来操作 Microsoft Office
? 用 Jython 写 Python 和 Java 的程序
?


23.1 Web 服务


23.1.1 Yahoo!金融股票报价服务器


23.2 用 Win32 的 COM 来操作 Microsoft Office

猜你喜欢

转载自www.cnblogs.com/effortsing/p/9982246.html