您的位置:首页 > 编程语言 > Python开发

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

2015-09-25 16:42 886 查看
函数 是组织好的、可重复使用的、用来实现单一或相关联功能的代码段。

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

函数的定义:
def test0():
"函数_文档字符串"
print('函数内部')

print(test0.__doc__)  # 函数_文档字符串


若采用默认参数定义函数,调用函数时,缺省参数的值如果没有传入,则被认为是默认值:
def test1(arg1='参数一', arg2='参数二'):
print('arg1:'+arg1)
print('arg2:'+arg2)

test1()  # arg1:参数一  arg2:参数二

# 默认情况下,参数值和参数名称是按函数声明中定义的的顺序匹配起来的
test1('ice', 'cream')  # arg1:ice  arg2:cream
test1(arg2='cream', arg1='ice')  # arg1:ice  arg2:cream


不定长参数。加了星号(*)的变量名会存放所有未命名的变量参数。选择不多传参数也可:
def test2(*args, param):
print(len(args))
for arg in args:
print(arg)
print(param)

test2(1, 2, 3, 4, param='This is param')

def test3(param, *args):
print(param)
print(len(args))
for arg in args:
print(arg)

test3('This is param', 1, 2, 3, 4)


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

mylist = [1, 2, 3, 4]
test4(mylist)
print(mylist)

# 输出:
# [1, 2, 3, 4]
# []
# []


return语句[表达式]退出函数,选择性地向调用方返回一个表达式。不带参数值的return语句返回None
def test5():
return (1, 2, 3, 4)

def test6():
return 1, 2, 3, 4

def test7():
return [1, 2, 3, 4]

result = test5()
print(result)  # (1, 2, 3, 4)

result = test6()
print(result)  # (1, 2, 3, 4)

result = test7()
print(result)  # [1, 2, 3, 4]


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

def outerFunc():
print('Outer Funtion')
def innerFunc():
print('Inner Function')
innerFunc()

outerFunc()

# 输出:
# Outer Funtion
# Inner Function


函数变量作用域

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

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

def test8():
"全局变量可以在整个程序范围内访问"
print(temp)

def test9():
inner_temp = 'ice'
print(inner_temp)

print(temp)  # ice cream
test8()  # ice cream
test9()  # ice

# 局部变量只能在其被声明的函数内部访问
print(inner_temp)  # 报错  name 'inner_temp' is not defined

def test10():
print(temp)  # 报错  local variable 'temp' referenced before assignment
temp = 'ice'
print(temp)


Python闭包

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

tempFunc = FuncX(3)
result = tempFunc(5)
print(result)  # 15

result = FuncX(3)(5)
print(result)  # 15


匿名函数

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

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

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

使用如下:
square = lambda x : x**2
print(square(3))  # 9

sum = lambda  x, y : x + y
print(sum(2, 3))  # 5


内置函数filter的使用:

官方文档内容如下:

filter(function, iterable)

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 的元素
reslut = filter(None, [1, 0, False, True])
print(list(reslut))  # [1, True]

def odd(num):
return num % 2

reslut = filter(odd, range(10))
print(list(reslut))  # [1, 3, 5, 7, 9]

reslut = filter(lambda num: num % 2, range(10) )
print(list(reslut))  # [1, 3, 5, 7, 9]


博客园博客:欠扁的小篮子
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: