函数的作用域、匿名函数
程序员文章站
2023-12-21 23:40:40
...
函数的作用域、匿名函数
函数的作用域在函数定义时已经确定,与函数在哪里调用无关!
【注:】直接print函数名,不带括号时,会打印出该函数的内存地址,若带括号,代表打印函数的全部执行过程和返回结果
例1:当函数 bar() 中已定义变量name时
name = 'aaa'
def foo():
name = 'bbb'
def bar():
name = 'ccc'
print(name)
return bar
print(foo)
print(foo())
foo()()
# <function foo at 0x00000000006C1378>
# <function foo.<locals>.bar at 0x00000000006C1400>
# ccc
例2:当函数 bar() 中未定义变量name时,向bar()外侧逐层寻找变量name的值
name = 'aaa'
def foo():
name = 'bbb'
def bar():
# name = 'ccc'
print(name)
return bar
foo()()
# bbb
例3:
name = 'aaa'
def foo():
name = 'bbb'
def bar():
name = 'ccc'
# print(name)
def tt():
print(name)
return 'ok'
return tt
return bar
a = foo()
b = foo()()
c = foo()()()
print(a)
print(b)
print(c)
# ccc
# <function foo.<locals>.bar at 0x0000000000831400>
# <function foo.<locals>.bar.<locals>.tt at 0x00000000008318C8>
# ok
匿名函数
例1:
name = ['alex','wupeiqi','LINHAIFENG']
f = lambda x:x.isupper()
print(f(name[0]))
print(f(name[2]))
# False
# True
例2:
func = lambda x,y,z:(x+y)**z
print(func(1,2,2))
# 9
例3: 当需要返回多个对象时,前后需要加小括号,将多个对象组成元祖,否则报错
func = lambda x,y,z:(x+1,y+2,z+3)
print(func(1,2,3))
# (2, 4, 6)