4.把函数当作对象
4.1闭包
#计算移动平均值
def make_averager():
count = 0
total = 0
def averager(new_value):
nonlocal count, total
count += 1
total += new_value
return total / count
return averager
#test
ave = make_averager()
ave(10)
ave(20)
4.2装饰器
#一个简单的装饰器,支持处理关键字参数
import time
DEFAULT_FMT = '[{elasped:0.8f}s] {name} {name}({args}) -> {result}'
def clock(fmt=DEFAULT_FMT):
def decorate(func):
def clocked(*_args):
t0 = time.time()
_result = func(*_args)
elasped = time.time() - t0
name = func.__name__
args = ', '.join(repr(arg) for arg in _args)
result = repr(_result)
print(fmt.format(**locals()))
return _result