闭包 匿名函数 装饰器 偏函数
##closure
#
def calc_sum(*args):
ax = 0
for n in args:
ax += n
return ax
def lazy_sum(*args):
def sum():
ax = 0
for n in args:
ax += n
return ax
return sum
f = lazy_sum(1, 3, 5, 7, 9)
print(f)
print(f())
def count():
fs = []
for i in range(1, 4):
def f():
return i*i
fs.append(f)
return fs
f1, f2, f3 = count()
print(f1(), f2(), f3())
def count():
def f(j):
def g():
return j * j
return g
fs = []
for i in range(1, 4):
fs.append(f(i)) #f(i)立刻被执行
return fs
f1, f2, f3 = count()
print(f1(), f2(), f3())
def createCounter():
num = 0
def counter():
nonlocal num
num += 1
return num
return counter
f = createCounter()
print(f())
print(f())
f2 = createCounter()
print(f2(), f2(), f2())
##lambda
#
print(list(map(lambda x: x * x, [1, 2, 3, 4, 5, 6, 7, 8, 9])))
f = lambda x : x * x
print(f)
def build(x, y):
return lambda: x * x + y *y
print(build(1, 3)())
##用匿名函数改造
def is_odd(n):
return n % 2 == 1
L1 = list(filter(is_odd, range(1, 20)))
L2 = list(filter(lambda n : n % 2 == 1, range(1, 20)))
print('?', L1, L2)
##decorator
#
def now():
print('2015-3-25')
f = now
print(f())
print(now.__name__)
print(f.__name__)
def log(func):
def wrapper(*args, **kw):
print('call %s():' % func.__name__)
return func(*args, **kw)
return wrapper
@log
def now():
print('2015-3-25')
now()
##更复杂的decorator
def log(text):
def decorator(func):
def wapper(*args, **kw):
print('%s %s():' % (text, func.__name__))
return func(*args, **kw)
return wapper
return decorator
@log('excute')
def now():
print('greater:', '2015-3-25')
now()
print(now.__name__)
##更好的decorator
import functools
def log(text):
def decorator(func):
@functools.wraps(func)
def wapper(*args, **kw):
print('%s %s():' % (text, func.__name__))
return func(*args, **kw)
return wapper
return decorator
@log('excute')
def now():
print('greater:', '2015-3-25')
print(now.__name__)
##练习
import time
import functools
def time_decorator(func):
@functools.wraps(func)
def wapper(*args, **kw):
now_mills = time.time() * 1000
print('%s executed in %s ms' % (func.__name__, now_mills))
return func(*args, **kw)
return wapper
@time_decorator
def any_func(*c):
temp = [str(s) + '!' for s in c ]
print(type(temp))
print('hello:', temp)
any_func(('Alice', 'Aha'))
print(any_func.__name__)
##Partial function
#
print(int('01234'))
print(int('1234', base = 8))
def int2(x):
return int(x, base = 2)
print(int2('10000'))
print(int('10000', 2))
import functools
int2 = functools.partial(int, base = 2)
print(int2('100000'))
max2 = functools.partial(max, 10)
print(max2(1, 2, 3, 9))
网友评论