def_odd_list(): n = 1 whileTrue: n = n + 2 yield n
def_no_division(n): returnlambda x: x % n > 0 defprimes(): yield2 it = _odd_list() whileTrue: n = next(it) yield n it = filter(_no_division(n), it) for n in primes(): if n < 1000: print(n) else: break
返回函数
python可以把函数作为返回值返回
1 2 3 4 5 6 7 8 9 10
defdo_later(*arg): defsum(): sum = 0 for element in arg: sum += element return sum return sum
defdo_later(): fs = [] for i in range(3): defmultiply(): return i * i fs.append(multiply) return fs f1, f2, f3 = do_later() print(f1()) print(f2()) print(f3())
defmultiply(x, y): return x * y multiply10 = functools.partial(multiply, y = 10) multiply2 = functools.partial(multiply, x = 2) print(multiply10(10)) print(multiply2(y=4))
# 会报错 print(multiply2(4))
通过上面的代码,我们通过functools.partial,将某个函数的参数设置为一个固定值,这样可以满足对某些特定意义的函数要求,很方便的进行调用。会报错的语句是因为赋值是按照顺序来的,multiply2的时候,x已经有固定值为2,按照顺序,调用语句会再给x做一次赋值,这一次是4,导致TypeError: multiply() got multiple values for argument ‘x’
装饰器
1 2
defprintname(): print('Sherlock Blaze')
有上述函数定义,当我们想在输出Sherlock Blaze 之前,输出一些日志,比如先输出,who’s the most handsome man。但是又不想修改printname函数的定义,这个时候,我们可以通过装饰器来包装一下这个函数,达到我们想要的效果。
1 2 3 4 5 6 7 8 9 10 11
deflog(func): defwrapper(*arg, **kw): print('who\'s the most handsome man.') return func(*arg, **kw) return wrapper