函数的作用域、匿名函数和函数式编程

一、作用域

LEGB原则

L (Local) 局部作用域
E (Enclosing) 闭包函数外的函数中
G (Global) 全局作用域
B (Built-in) 内建作用域

python按照LEGB原则搜索变量,即优先级L>E>G>B

1.

def test1():
    print("in the test1")
def test():
    print("in the test")
    return test1      #返回函数名

test()
res = test()
print(res())
#也可以使用test()()

 输出结果:

in the test  #输出1
in the test   #输出2
in the test1   #输出3
None            #输出4

分析:

输出1即为test()函数print打印出来的结果

输出2res为test函数的返回值test1【函数名】

输出3为打印test1函数的print的内容

输出4是由于test1函数没有return返回值,即输出None

2.

 1 name = "alex"
 2 def foo():
 3     name = "xiaoshagua"
 4     def bar():
 5         name = "hxq"
 6         def tt():
 7             print(name)
 8         return tt
 9     return bar
10 
11 a = foo()
12 print(a)
13 b = a()
14 print(b)
15 b()

输出结果:

1 <function foo.<locals>.bar at 0x00000172973F4EA0>
2 <function foo.<locals>.bar.<locals>.tt at 0x00000172973F4F28>
3 hxq

分析:

第一个输出为bar函数的内存地址,调用foo函数,返回bar的地址再赋值给a

第二个输出为tt函数的内存地址,调用bar函数,返回tt的地址再赋值给b

第三个输出是调用tt函数,打印name的值“hxq”

二、匿名函数

当需要使用一些简单的函数时,不需要显式地定义函数,直接传入匿名函数更方便。

python中有lambda关键字表示匿名函数

lambda x:x + 1

lambda为关键字,代表这是一个匿名函数,冒号前的x是形参,冒号后的表达式是匿名函数的返回值 ,类似于定义函数的return

例如:

func = lambda x:x + 1
print(func(10))

结果:

11

由此可见lambda匿名函数和定义式函数功能是一样的,不过匿名函数较为简洁

匿名函数一般与函数连用

 三、函数式编程

形参传入的是函数,或者返回值为函数。只要输入是确定的,那么输出也是确定的。

函数式内部不用变量

 1 #函数作为参数
 2 def test1(name):
 3     print("my name is %s"%name)
 4 
 5 def test2(s):
 6     print(s)
 7 
 8 test2(test1("Mary"))
 9 
10 #函数作为返回值
11 def test3():
12     print("test3")
13     return test4()
14 
15 def test4():
16     print("test4")
17 
18 test3()

 结果:

1 my name is Mary
2 None
3 test3
4 test4

这两种函数称为高阶函数

尾调用:在函数的最后一步调用另一个函数

最后一步不一定是最后一行

例如:

 1 def test1():
 2     print("hello")
 3 
 4 def test2():
 5     print("world")
 6 
 7 def test3(x):
 8     if type(x) is str:
 9         return test1()
10     else:
11         return test2()
12     

一定要是最后一步:有的函数的返回值可能是两步,一定要注意

1 def test1():
2    return "hello, world!"
3 
4 def test2(x):
5     return test1() + x
6 
7 #这个并不是在最后一步调用了另一个函数,它其实是两步,一步运行test1,一步拼接x

map函数

map() 会根据提供的函数对指定序列做映射。

第一个参数 function 以参数序列中的每一个元素调用 function 函数,返回包含每次 function 函数返回值的新列表。

1 s = [1, 5, 7, 9, 2, 10]
2 def square(x):
3     return x**2
4 
5 print(list(map(square, s)))

结果:

1 [1, 25, 49, 81, 4, 100]

filter函数

filter() 函数用于过滤序列,过滤掉不符合条件的元素,返回由符合条件元素组成的新列表。

该接收两个参数,第一个为函数,第二个为序列,序列的每个元素作为参数传递给函数进行判断,然后返回 True 或 False,最后将返回 True 的元素放到新列表中。

date = [1, 2, 3, 4, 5, 6, 7, 8, 9]

def de(s):
    return s % 2 == 1

print(list(filter(de, date)))

结果:

[1, 3, 5, 7, 9]

reduce函数

reduce() 函数会对参数序列中元素进行累积。

函数将一个数据集合(链表,元组等)中的所有数据进行下列操作:用传给 reduce 中的函数 function(有两个参数)先对集合中的第 1、2 个元素进行操作,得到的结果再与第三个数据用 function 函数运算,最后得到一个结果。

1 num = [1, 2, 3, 4, 5]
2 
3 def add(x, y):
4     return x + y
5 
6 print(reduce(add, num))

结果:

1 15

猜你喜欢

转载自www.cnblogs.com/hexiaoqi/p/9337829.html
今日推荐