函数式编程 与 变量的作用域


Python 搜索局部变量 x 失败,然后在属于另一个函数的外层作用域里寻找。变量 x 是函数 outer 的局部变量,但函数 inner 仍然有外层作用域的访问权限(至少有读和修改的权限)

>>> def o():
...     x=1
...     def i():
...         print(x)
...     i()
>>> o()
1

变量作用域:
>>> a="xss"
>>> def foo():
...      print(a)
>>> foo()
xss
>>> def foo():
...      print(locals())
...      print(globals())
>>> foo()
{}
{'foo': <function foo at 0x00895660>, '__spec__': None, 'a': 'xss', '__package__': None, '__name__': '__main__', '__doc__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__builtins__': <module 'builtins' (built-in)>}

函数式编程:

把函数当变量传进来然后用()来调用。

>>> def add(x, y):
...     return x + y
>>> def apply(func, x, y): # 1
...     return func(x, y) # 2
>>> apply(add, 2, 1) # 3
3

>>> def outer():
···    print("xss")
...     def inner():
...         print "Inside inner"
...     return inner # 1
>>> foo = outer()
xss 
>>> foo()
Inside inner

闭包:

闭包是指在 JavaScript 中,内部函数总是可以访问其所在的外部函数中声明的参数和变量,即使在其外部函数被返回(寿命终结)了之后。闭包通常用来创建内部变量,使得这些变量不能被外部随意修改,同时又可以通过指定的函数接口来操作。


最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容