def func(): print(‘from func‘) print(func) # 函数名和函数体代码就是存放一个内存地址中,所以打印时会直接输出内存地址<function func at 0x0000000000411E18> print(id(func)) f = func # 将函数名传递给另一个变量名,从此时开始f也是一个函数名了 func() print(f) f() # 其实指向的也是函数func指向函数体代码的内存地址
def index(): print(‘index‘) def func(): print(‘func‘) return index # 返回为index的内存 res = func() print(res) # 打印为index的内存地址 res() # 调用index函数体代码
def func(): print(‘func‘) print(funnc()) l = [1,2,func,func()] # [1,2,<function func at 0x000001F7D79899D8>,None] print(l)
def my_max(x,y): if x > y: return x return y def my_max4(a,b,c,d): res1 = my_max(a,b) res2 = my_max(res1,c) res3 = my_max(res2,d) return res3 print(my_max4(34,2,130,4))
def outer(): x = 1 print(‘outer‘) def inner(): print(‘inner‘) # print(inner) return inner res = outer() # 强行打印outer() 输出‘outer‘,但是返回值返回的是index的内存地址 # print(res) res() # 借以调用index()来输出‘inner‘
调用一个函数以实现另一个函数的代码功能
**************************************************** 重点理解*********************************************************
x=111 def outer(): def inner(): print(‘from inner‘,x) return inner f=outer() def func(): x=333 f() # 虽然f()到现在才调用但是它不会从当前的位置查找x的地址和值,而是会从f()也就是index()的定义阶段开始查找 func() #最后输出111,而不是333
说明,局部命名空间中的变量名在其中寻不到值和地址时,函数查找名字的顺序并不会因为 函数调用的位置而改变,而是依旧按照定义时的位置以局部到全局到内置的顺序来查找名字,不会从调用函数的位置按照正确的顺序来查找名字
# global 在局部修改全局的不可变数据类型 # x = [] # 因为列表是可变类型 x = 10 # 不可变类型 username = ‘messi‘ def func(): global x,username # 修改全局变量 而不是创建局部名称空间 x = 24 username = ‘kobe‘ func() print(x) print(username)
# nonlocal 局部修改局部 def func(): x = 1 def index(): nonlocal x x = 2 print(x) index() print(x) # 本来应该返回的是1,但是nonlobal修改了局部的变量所以就输出了2 func()
原文:https://www.cnblogs.com/ITchemist/p/11167391.html