一、匿名函数
1. 匿名函数
python中除了用def关键字来声明函数之外,还有用lambda声明函数,这样的函数叫做匿名函数。
2. 简单函数转为匿名函数
匿名函数语法: lambda 参数:表达式
# 0参数
# 简单函数可以用匿名函数
def test():
return "hello world"
a = test()
print(a) # hello world
# 匿名函数语法: lambda 参数:表达式
test = lambda: "hello world"
b = test()
print(b) # hello world
# 传入参数
def test2(num1, num2):
return num1+num2
res = test2(1, 2)
print(res) # 3
# 匿名函数
test2 = lambda num1, num2: num1+num2
res = test2(1, 2)
print(res) # 3
3.过滤器与匿名函数的结合
# 过滤器filter(func, 可迭代对象)
li = [12, 63, 78, 90, 2, 45, 23]
def test3(x):
return x > 50
res = filter(test3, li)
print(res) # <filter object at 0x000001E992A45348>
print(list(res)) # [63, 78, 90]
# 转成匿名函数
res = filter(lambda x: x > 50, li)
print(res) # <filter object at 0x000002DA4CE25588>
print(list(res)) # [63, 78, 90]
4.匿名函数作为参数传入函数中的使用
当我们做一个简单的运算的时候,可以直接用匿名函数
test = lambda num1, num2: num2 + num1
print(test(1, 2)) # 3
虽然这个函数可以达到运算加法的目的,但是有缺点:适应性不强,只能做到加法的运算
我们可以通过一步步改造完善这个运算,可以做个简单的计算器
def test4(a, b, func):
res = func(a, b)
return res
# 将lambda匿名函数作为参数传入,较之前灵活了,适应性加强了
num = test4(4, 5, lambda a, b: a * b)
print(num) # 20
当我们把匿名函数作为参数,传入到函数的调用的时候,可以通过改变参数func,进行加减乘除的运算,但是这样传入的参数实用性还是不是很强,将func用input,那么就更加方便了
# 实现匿名函数的输入,这样更加灵活了,且适应性更强了
func = input("请输入一个匿名函数:")
func = eval(func)
def test4(a, b, func):
res = func(a, b)
return res
res4 = test4(23, 87, func)
print(res4)
以上这段代码实用性更加强了,但是还是存在缺陷,run一次只能计算一次,没办法连续使用,这样我们用死循环就可以解决这个问题
while True:
flag = input("退出请按[y/q]:")
if flag != "q" and flag != "y":
func = eval(input("请输入一个匿名函数:"))
num1 = int(input("请输入num1:"))
num2 = int(input("请输入num2:"))
def test5(num1, num2, func):
return func(num1, num2)
res = test4(num1, num2, func)
print(res)
else:
break
二、函数的作用域
1.定义的变量所能作用的范围
2. 全局变量 函数外部定义的变量是全局变量
a = "hello world" # 全局变量
def test():
a = "hello" # 局部变量
print("1:", a)
print("2:", a) # 2: hello world
test() # 1: hello 1在2后面是因为,test函数是在2后面调用的
print("3:", a) # 3: hello world
# 在函数外部定义的变量
在函数内部定义全局变量 global
a = "hello world" # 全局变量
def test():
global a
a = "hello" # 局部变量
print("1:", a)
print("2:", a) # 2: hello world
test() # 1: hello
print("3:", a) # 3: hello
3. 局部变量 在函数内部定义的变量
由上例子我们可以知道,局部变量是不能作用到函数外面的
4. nonlocal
这个用在函数嵌套函数中
# nonlocal
1 def test_out():
2 str1 = "hello hello"
3 def test_in():
4 str1 = "hello"
5 str1 += " world"
6 print("1:", str1) # 1: hello world
7 test_in()
8 print("2:", str1) # 2: hello hello
test_out()
当test_out()函数被调用的时候,函数从上到下执行,当执行了第7行代码的时候,test_in函数被调用,执行到了第6行代码的时候,就print了“hello world”,再执行第8行代码的时候,打印了hello hello,相对与str1 = "hello"来书,str2 = "hello hello"变量作用范围更广,而后者相对与前者是一个局部变量,所以函数test_in不被外面调用
如果我们想要在内层函数调用外层函数,我们需要用到nonlocal
def test_out():
str1 = "hello hello"
def test_in():
# str1 = "hello"
nonlocal str1
str1 += " world"
print("1:", str1) # 1: hello hello world
test_in()
print("2:", str1) # 2: hello hello world
test_out()
总结:
1. 函数内部定义的为局部变量,其作用域是局部作用域,函数外无法调用的
2.函数外定义的为全局变量,其作用域是全局作用域,如果在函数内想要进行修改,需要global
3.外层函数的变量,如果想要在内层进行修改,需要nonlocal