exit

exit([status]) 调⽤用所有退出函数后终⽌止进程,并返回 ExitCode。
• 忽略或 status = None,表⽰示正常退出, ExitCode = 0。
• status = <number>,表⽰示 ExiCode = <number>。
• 返回⾮非数字对象表⽰示失败,参数会被显⽰示, ExitCode = 1。

$ cat main.py
#!/usr/bin/env python
#coding=utf-8
import atexit
def clean():
! print "clean..."
def main():
! atexit.register(clean)
! exit("Failure!")
if __name__ == "__main__":
main()
$ ./main.py
Failure!
clean...
$ echo $?
1
sys.exit() 和 exit() 完全相同。os._exit() 直接终⽌止进程,不调⽤用退出函数,且退出码必须是数字

参数传递

用 *args 收集 "多余" 的位置参数,**kwargs 收集 "额外" 的命名参数。这两个名字只是惯例,可自由命名
>>> def test(a, b, *args, **kwargs):
... print a, b
... print args
... print kwargs
>>> test(1, 2, "a", "b", "c", x = 100, y = 200)
1 2
('a', 'b', 'c')
{'y': 200, 'x': 100}
变参只能放在所有参数定义的尾部,且 **kwargs 必须是最后⼀一个
>>> def test(*args, **kwargs):! ! ! # 可以接收任意参数的函数。
... print args
... print kwargs
>>> test(1, "a", x = "x", y = "y")! ! # 位置参数,命名参数。
(1, 'a')
{'y': 'y', 'x': 'x'}
>>> test(1)! ! ! ! ! ! # 仅传位置参数。
(1,)
{}
>>> test(x = "x")! ! ! ! ! # 仅传命名参数。
()
{'x': 'x'}
单个 "*" 展开序列类型,或者仅是字典的主键列表。"**" 展开字典键值对。但如果没有变参收集,
展开后多余的参数将引发异常。
>>> def test(a, b):
... print a
... print b
>>> d = dict(a = 1, b = 2)
>>> test(*d)    # 仅展开 keys(),test("a"、"b")。
a
b
>>> test(**d)    # 展开 items(),test(a = 1, b = 2)。
1
2
>>> d = dict(a = 1, b = 2, c = 3)
>>> test(*d)    # 因为没有位置变参收集多余的 "c",导致出错。
TypeError: test() takes exactly 2 arguments (3 given)
>>> test(**d)    # 因为没有命名变参收集多余的 "c = 3",导致出错。
TypeError: test() got an unexpected keyword argument 'c'

闭包

闭包是指:当函数离开创建环境后,依然持有其上下⽂文状态。⽐比如下⾯面的 a 和 b,在离开 test 函数
后,依然持有 test.x 对象。
>>> def test():
... x = [1, 2]
... print hex(id(x))
...
... def a():
... x.append(3)
... print hex(id(x))
...
... def b():
... print hex(id(x)), x
...
... return a, b
>>> a, b = test()
0x109b925a8     # test.x
>>> a()
0x109b925a8     # 指向 test.x
>>> b()
0x109b925a8 [1, 2, 3]

yield

yield 的作用就是把一个函数变成一个 generator,带有 yield 的函数不再是一个普通函数,Python 解释器会将其视为一个 generator,调用 fab(5) 不会执行 fab 函数,而是返回一个 iterable 对象!在 for 循环执行时,每次循环都会执行 fab 函数内部的代码,执行到 yield b 时,fab 函数就返回一个迭代值,下次迭代时,代码从 yield b 的下一条语句继续执行,而函数的本地变量看起来和上次中断执行前是完全一样的,于是函数继续执行,直到再次遇到 yield。


>>> def consumer():
... while True:
... d = yield
... if not d: break
... print "consumer:", d
>>> c = consumer()  # 创建消费者
>>> c.send(None)  # 启动消费者
>>> c.send(1)  # ⽣生产数据,并提交给消费者。
consumer: 1
>>> c.send(2)
consumer: 2
>>> c.send(3)
consumer: 3
>>> c.send(None)  # ⽣生产结束,通知消费者结束。
StopIteration



chain

连接多个迭代器。
>>> it = chain(xrange(3), "abc")
>>> list(it)
[0, 1, 2, 'a', 'b', 'c']

combinations

combinations
返回指定⻓长度的元素顺序组合序列。
>>> it = combinations("abcd", 2)
>>> list(it)
[('a', 'b'), ('a', 'c'), ('a', 'd'), ('b', 'c'), ('b', 'd'), ('c', 'd')]
>>> it = combinations(xrange(4), 2)
>>> list(it)
[(0, 1), (0, 2), (0, 3), (1, 2), (1, 3), (2, 3)]
combinations_with_replacement 会额外返回同⼀一元素的组合。
>>> it = combinations_with_replacement("abcd", 2)
>>> list(it)
[('a', 'a'), ('a', 'b'), ('a', 'c'), ('a', 'd'), ('b', 'b'), ('b', 'c'), ('b', 'd'),
('c', 'c'), ('c', 'd'), ('d', 'd')]

permutations

permutations
与 combinations 顺序组合不同,permutations 让每个元素都从头组合⼀一遍。
>>> it = permutations("abc", 2)
>>> list(it)
[('a', 'b'), ('a', 'c'), ('b', 'a'), ('b', 'c'), ('c', 'a'), ('c', 'b')]
>>> it = combinations("abc", 2)
>>> list(it)
[('a', 'b'), ('a', 'c'), ('b', 'c')]



product

product
让每个元素都和后⾯面的迭代器完整组合⼀一遍。
>>> it = product("abc", [0, 1])
>>> list(it)
[('a', 0), ('a', 1), ('b', 0), ('b', 1), ('c', 0), ('c', 1)]




compress

按条件表过滤迭代器元素。
>>> it = compress("abcde", [1, 0, 1, 1, 0])
>>> list(it)
['a', 'c', 'd']



count

从起点开始,"⽆无限" 循环下去。
>>> for x in count(10, step = 2):
... print x
... if x > 17: break
10
12
14
16
18



cycle

迭代结束,再从头来过。
>>> for i, x in enumerate(cycle("abc")):
... print x
... if i > 7: break
a
b
c
a
b
c
a
b
c

groupby

将连续出现的相同元素进⾏行分组
>>> [list(k) for k, g in groupby('AAAABBBCCDAABBCCDD')]
[['A'], ['B'], ['C'], ['D'], ['A'], ['B'], ['C'], ['D']]
>>> [list(g) for k, g in groupby('AAAABBBCCDAABBCCDD')]
[['A', 'A', 'A', 'A'], ['B', 'B', 'B'], ['C', 'C'], ['D'], ['A', 'A'], ['B', 'B'], ['C',
'C'], ['D', 'D']]

ifilter

ifilter
与内置函数 filter() 类似,仅保留符合条件的元素。
>>> it = ifilter(lambda x: x % 2, xrange(10))
>>> list(it)
[1, 3, 5, 7, 9]
ifilterfalse 正好相反,保留不符合条件的元素。
>>> it = ifilterfalse(lambda x: x % 2, xrange(10))
>>> list(it)
[0, 2, 4, 6, 8]

repeat

repeat
将⼀一个对象重复 n 次。
>>> it = repeat("a", 3)
82
>>> list(it)
['a', 'a', 'a']