forked from misakar/pythonCookbook
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path7.10.2.py
More file actions
33 lines (24 loc) · 704 Bytes
/
7.10.2.py
File metadata and controls
33 lines (24 loc) · 704 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
# -*- coding: utf-8 -*-
# 单个方法的类
class ResultHandler:
def __init__(self):
"""保留sequence变量"""
self.sequence = 0
def handler(self, result):
self.sequence += 1
print ("[{}] Got: {}".format(self.sequence, result))
# 闭包函数替代
def result_handler():
# 利用闭包保存 sequence 变量
sequence = 0
def handler(result):
nonlocal sequence
sequence += 1
print ("[{}] Got: {}".format(sequence, result))
return handler
def apply_async(func, args, *, callback):
result = func(*args)
callback(result)
def add(x, y):
return x + y
apply_async(add, (2, 4), callback=result_handler())