python中函数中定义函数

from functools import reduce
def wrapper():
    alist=range(1,101)
    def lazy_sum():
        return reduce(lambda x,y:x+y,alist)
    return lazy_sum
pp = wrapper()
print (pp) 
print (pp())

输出结果如下:

<function wrapper.<locals>.lazy_sum at 0x000001EE74B95488>

5050

在pp中,return的相当于是lazy_sum函数,只是指定了这个函数。加了括号之后,相当于对函数传入了变量。因此进行运算。

值得注意的是,定义函数时,如果没有变量传入时,这个括号不能省略

但注意的是不能直接调用函数里面定义的函数,如下列

l1 = lazy_sum()
Traceback (most recent call last):

  File "<ipython-input-3-6c08b727c1e2>", line 1, in <module>
    l1 = lazy_sum()

NameError: name 'lazy_sum' is not defined

环境: python3.6

注: Python3将很多原有的函数打包,放到functools package中。 



猜你喜欢

转载自blog.csdn.net/qq_31761357/article/details/80245879