前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >python3 入门 (三) 函数与lambda表达式、闭包

python3 入门 (三) 函数与lambda表达式、闭包

作者头像
欠扁的小篮子
发布2018-04-11 11:17:12
1K0
发布2018-04-11 11:17:12
举报
文章被收录于专栏:技术碎碎念技术碎碎念

函数 是组织好的、可重复使用的、用来实现单一或相关联功能的代码段。

  • 函数代码块以def关键词开头,后接函数标识符名称和圆括号()
  • 任何传入参数和自变量必须放在圆括号中间。圆括号之间可以用于定义参数
  • 函数的第一行语句可以选择性地使用文档字符串—用于存放函数说明
  • 函数内容以冒号起始,并且缩进
  • Return[expression]结束函数,选择性地返回一个值给调用方。不带表达式的return相当于返回 None

函数的定义:

代码语言:javascript
复制
1 def test0():
2     "函数_文档字符串"
3     print('函数内部')
4 
5 print(test0.__doc__)  # 函数_文档字符串

若采用默认参数定义函数,调用函数时,缺省参数的值如果没有传入,则被认为是默认值:

代码语言:javascript
复制
1 def test1(arg1='参数一', arg2='参数二'):
2     print('arg1:'+arg1)
3     print('arg2:'+arg2)
4 
5 test1()  # arg1:参数一  arg2:参数二
6 
7 # 默认情况下,参数值和参数名称是按函数声明中定义的的顺序匹配起来的
8 test1('ice', 'cream')  # arg1:ice  arg2:cream
9 test1(arg2='cream', arg1='ice')  # arg1:ice  arg2:cream

不定长参数。加了星号(*)的变量名会存放所有未命名的变量参数。选择不多传参数也可:

代码语言:javascript
复制
 1 def test2(*args, param):
 2     print(len(args))
 3     for arg in args:
 4         print(arg)
 5     print(param)
 6 
 7 test2(1, 2, 3, 4, param='This is param')
 8 
 9 
10 def test3(param, *args):
11     print(param)
12     print(len(args))
13     for arg in args:
14         print(arg)
15 
16 test3('This is param', 1, 2, 3, 4)

所有参数(自变量)在Python里都是按引用传递。如果在函数里修改了参数,那么在调用这个函数的函数里,原始的参数也被改变了

代码语言:javascript
复制
 1 def test4(mylist):
 2     print(mylist)
 3     mylist.clear()
 4     print(mylist)
 5 
 6 mylist = [1, 2, 3, 4]
 7 test4(mylist)
 8 print(mylist)
 9 
10 # 输出:
11 # [1, 2, 3, 4]
12 # []
13 # []

return语句[表达式]退出函数,选择性地向调用方返回一个表达式。不带参数值的return语句返回None

代码语言:javascript
复制
 1 def test5():
 2     return (1, 2, 3, 4)
 3 
 4 
 5 def test6():
 6     return 1, 2, 3, 4
 7 
 8 
 9 def test7():
10     return [1, 2, 3, 4]
11 
12 result = test5()
13 print(result)  # (1, 2, 3, 4)
14 
15 result = test6()
16 print(result)  # (1, 2, 3, 4)
17 
18 result = test7()
19 print(result)  # [1, 2, 3, 4]

内部函数。函数体内可以再定义函数:

代码语言:javascript
复制
 1 def outerFunc():
 2     print('Outer Funtion')
 3     def innerFunc():
 4         print('Inner Function')
 5     innerFunc()
 6     
 7 outerFunc()
 8 
 9 # 输出:
10 # Outer Funtion
11 # Inner Function

函数变量作用域

定义在函数内部的变量拥有一个局部作用域,定义在函数外的拥有全局作用域。

局部变量只能在其被声明的函数内部访问,而全局变量可以在整个程序范围内访问。调用函数时,所有在函数内声明的变量名称都将被加入到作用域中

代码语言:javascript
复制
 1 temp = 'ice cream'
 2 
 3 def test8():
 4     "全局变量可以在整个程序范围内访问"
 5     print(temp)
 6 
 7 
 8 def test9():
 9     inner_temp = 'ice'
10     print(inner_temp)
11 
12 print(temp)  # ice cream
13 test8()  # ice cream
14 test9()  # ice
15 
16 
17 # 局部变量只能在其被声明的函数内部访问
18 print(inner_temp)  # 报错  name 'inner_temp' is not defined
19 
20 def test10():
21     print(temp)  # 报错  local variable 'temp' referenced before assignment
22     temp = 'ice'
23     print(temp)

Python闭包

如果在一个内部函数里,对在外部作用域(但不是在全局作用域)的变量进行引用,那么内部函数就被认为是闭包(closure)。一个闭包就是你调用了一个函数A,这个函数A返回了一个函数B给你。这个返回的函数B就叫做闭包。你在调用函数A的时候传递的参数就是自由变量

代码语言:javascript
复制
 1 def FuncX(x):
 2     def FuncY(y):
 3         return x * y
 4     return FuncY
 5 
 6 tempFunc = FuncX(3)
 7 result = tempFunc(5)
 8 print(result)  # 15
 9 
10 result = FuncX(3)(5)
11 print(result)  # 15

匿名函数

python 使用 lambda 表达式来创建匿名函数

  • lambda只是一个表达式,函数体比def简单很多
  • lambda的主体是一个表达式,而不是一个代码块。仅仅能在lambda表达式中封装有限的逻辑进去
  • lambda函数拥有自己的名字空间,且不能访问自有参数列表之外或全局名字空间里的参数
  • 虽然lambda函数看起来只能写一行,却不等同于C或C++的内联函数,后者的目的是调用小函数时不占用栈内存从而增加运行效率

lambda函数的语法只包含一个语句: lambda [arg1 [,arg2,.....argn]]:expression

使用如下:

代码语言:javascript
复制
1 square = lambda x : x**2
2 print(square(3))  # 9
3 
4 sum = lambda  x, y : x + y
5 print(sum(2, 3))  # 5

内置函数filter的使用:

官方文档内容如下:

filter(functioniterable)

Construct an iterator from those elements of iterable for which function returns true. iterable may be either a sequence, a container which supports iteration, or an iterator. If function is None, the identity function is assumed, that is, all elements of iterable that are false are removed.

function参数可传入None、函数、lambda表达式,iterable参数传入一个可迭代对象。

若function参数为None:返回可迭代对象中所有不为False的元素

若function参数为函数或lambda表达式:返回  将元素作为函数参数、函数返回值为True  的元素

代码语言:javascript
复制
 1 reslut = filter(None, [1, 0, False, True])
 2 print(list(reslut))  # [1, True]
 3 
 4 def odd(num):
 5     return num % 2
 6 
 7 reslut = filter(odd, range(10))
 8 print(list(reslut))  # [1, 3, 5, 7, 9]
 9 
10 reslut = filter(lambda num: num % 2, range(10) )
11 print(list(reslut))  # [1, 3, 5, 7, 9]
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2015-09-25 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档