Python | Expert Python - Dongweiming

Python 高级编程 by 董韦明

1). global variable

1
2
3
4
5
6
7
8
9
>>> d = {'a': 1, 'b':2}
>>> # 粗暴的写法
>>> for k, v in d.iteritems():
... exec "{}={}".format(k, v) # Python3 exec()
...
>>> # 文艺的写法
>>> globals().update(d)
>>> a, b
(1, 2)

2). .format()

https://notes.lroolle.com/2016/03/26/Python-Format/

3). dict

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
# 操作字典

>>> dict((["a", 1], ["b", 2])) # ⽤两个序列类型构造字典
{'a': 1, 'b': 2}

>>> dict(zip("ab", range(2)))
{'a': 0, 'b': 1}

>>> dict(map(None, "abc", range(2)))
{'a': 0, 'c': None, 'b': 1}

>>> dict.fromkeys("abc", 1) # ⽤序列做 key,并提供默认 value
{'a': 1, 'c': 1, 'b': 1}

>>> {k:v for k, v in zip("abc", range(3))} # 字典解析
{'a': 0, 'c': 2, 'b': 1}

>>> d = {"a":1, "b":2}
>>> d.setdefault("a", 100) # key 存在,直接返回 value
1
>>> d.setdefault("c", 200) # key 不存在,先设置,后返回
200
>>> d
{'a': 1, 'c': 200, 'b': 2}

4). Iterator

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19


class MyIterator:
def __init__(self, *args):
self._data = list(*args)
self._index = 0

def __iter__(self):
return self

def __next__(self):
return self.next()

def next(self, data, index):
if self._index >= len(self._data):
raise StopIteration
data = self._data[self._index]
self._index += 1
return data

5). with 上下文管理

1
2
3
4
5
6
7
8
9
10
11
12
13
14

>>> import pymongo
>>> class Operation(object):
... def __init__(self, database,
... host='localhost', port=27017):

... self._db = pymongo.MongoClient(
... host, port)[database]
... def __enter__(self):
... return self._db
... def __exit__(self, exc_type, exc_val, exc_tb):
... self._db.connection.disconnect()
...
>>> with Operation(database='test') as db:
... print db.test.find_one()

6). contextmanager

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
>>> lock = threading.Lock()
>>> @contextmanager
... def openlock():
... print('Acquire')
... lock.acquire()
... yield
... print('Releasing')
... lock.release()
...
>>> with openlock():
... print('Lock is locked: {}'.format(lock.locked()))
... print 'Do some stuff'
...
Acquire
Lock is locked: True
Do some stuff
Releasing