Python Basics-nesting and closure of functions-namespaces and scopes
名称空间:Python所有有关命名的操作都是在操作名称空间,例如变量名,函数名 1、内置名称空间:Python解释器提供好的功能,解释器启动跟着一起启动,是全局作用域 2、全局名称空间:Python中顶行写的,不在函数内部定义的,都是全局名称空间,在运行的时候会产生名称空间,是全局作用域 3、局部名称空间:在一个小范围定义,只能当前范围及其子空间内运行,例如在函数内部定义的,是局部作用域
Ii. Nesting of functions
1、函数的嵌套调用2、函数的嵌套定义
1111111111111111def f1(): #x=1 print(‘------>f1 ‘,x) def f2(): #x = 2 print(‘---->f2 ‘,x) def f3(): x=3 print(‘-->f3 ‘,x) f3() f2()f1()
Third, the use of functions
1、函数可以被当做变量赋值
def foo(): print("foo")print(foo) #打印foo的内存地址空间,函数的名字在不带小括号时表示的是函数的内存地址f=foo #把foo的内存地址空间做值赋值给f变量print(f) #打印f,起始就是打印foo的内存地址空间f() #f()事实上就是执行foo函数,等同于foo()打印结果为<function foo at 0x0000000000B91378> #print(foo)的结果<function foo at 0x0000000000B91378> #print(f)的结果foo #执行f()的结果,实际就是执行foo()的结果
2. Functions can be passed as parameters
DefFoo(): Print ("foo") print (foo)#打印foo的内存地址空间f =foo#把foo的内存地址空间做值赋值给f变量print (f)#打印f, the start is to print Foo's memory address space F () #f () is actually executing the Foo function, equivalent to foo () def bar (func): Print (func) #这个是打印foo () The memory address of the function func () #func是foo的内存地址, plus () is actually executing the foo () function return FUNCF = Bar (foo) #这个是获取bar的返回值print (f) #打印f, that is, the return value of the print bar () is foo () memory address, same as print (func) f () #f是bar def bar (func): Print (func) bar (foo ( )) #这个是先执行foo () number of rows, execute the code in the function, print Foo First, and then pass the return value of Foo () as an argument to the bar () function to Bar,foo () no return value, so none Span class= "hljs-comment" > #结果就是先输出一个 "Foo" then Bar (none), pass none to Bar () function, print no
Closure: The code for an intrinsic function contains a reference to an external scope, but must not be a reference to the global scope, and the closure function must have a __closure__ method
x=1 def f1 (): x= 2 y=3 def f2 (): print (x) y return f2f=f1 () #f是f2的内存地址f () #f () is F2 (), You can guarantee that F2 () can be executed at any location without the scope restrictions print (f.__closure__) #打印结果是元组, The number of tuples represents the number of elements of the last function referenced by the closure print (F.__closure__[0]) #结果是元组, You can use the index to view print (F.__closure__[0].cell_contents) # View the value of the application's upper-level parameter corresponding to the specified tuple
def init(func): def wrapper(*args,**kwargs): res=func(*args,**kwargs) return res return wrapper
Nesting and closure of python/functions