Python内嵌函数与闭包

一、Python中没有过程,只有函数。

没有返回值的称为过程 。
一般我们称某个函数时整型函数,就是因为函数的返回值是整型。Python中只有函数,没有过程,所以Python中的函数都有返回值。
我们是通过return返回表达式。虽然有的函数没有return表达式,但是也有返回值。

def text():
	a=1
print(text())

None	#输出

没有return表达式时,返回值为none。


二、全局变量和局部变量

def discount(price,rate):
	final_price=price*rate
	return final_price
price=float(input('请输入商品的总价:'))
rate=float(input('请输入商品的折扣率:'))
new_price=discount(price,rate)
print('打折后商品的价格:',new_price)
print("打印final_price的值:",final_price)

#输出
请输入商品的总价:100
请输入商品的折扣率:0.8
打折后商品的价格: 80.0
NameError: name 'final_price' is not defined

final_price是局部变量,在函数外部无法访问。

def discount(price,rate):
	final_price=price*rate
	print("打印全局变量price的值:",price)
	return final_price
price=float(input('请输入商品的总价:'))
rate=float(input('请输入商品的折扣率:'))
new_price=discount(price,rate)
print("打折后的价格:",new_price)

#输出
请输入商品的总价:100
请输入商品的折扣率:0.8
打印全局变量price的值: 100.0
打折后的价格: 80.0

全局变量可以在任意部位访问。

如果在函数内部改变全局变量会出现什么情况呢?

def discount(price,rate):
	final_price=price*rate
	#print("打印全局变量price的值:",price)
	price=50
	print("修改全局变量price的值:",price)
	return final_price
price=float(input('请输入商品的总价:'))
rate=float(input('请输入商品的折扣率:'))
new_price=discount(price,rate)
print("打折后的价格:",new_price)
print("全局变量price的值:",price)

#输出
请输入商品的总价:100
请输入商品的折扣率:0.8
修改全局变量price的值: 50
打折后的价格: 80.0
全局变量price的值: 100.0

当我们在函数体内修改全局变量时,函数内会自动创建一个新的局部变量,而这个局部变量和全局变量的名字相同,所以第一个打印的price是局部变量,第二个price是全局变量,所以在函数内部最好不要修改它。但我们实在想要去改变全局变量的话,我们依然有办法改变它。
通过关键字global来在函数体内改变全局变量:

def fun1():
	global a
	a=10
	print(a)
a=5
fun1()
print(a)

#输出
10
10

三、内嵌函数

Python支持在一个函数内定义另外一个函数。

def fun1():
	print('fun1() is performing....')
	def fun2():
		print('fun2() is performing....')
	fun2()  #在fun1()中调用fun2()函数
fun1()

#输出
fun1() is performing....
fun2() is performing....

因为fun2()函数在fun1()之内,所以fun2()相似于是一个fun1()内的局部变量,那么fun2()在fun1()函数外是不可以被调用的。


四、闭包

def fun1(x):
	def fun2(y):
		return (x*y)
	return fun2

这个例子就是闭包,那么闭包到底是什么呢?
闭包从表现形式上定义为如果在一个内部函数里对外部作用域的变量进行引用(但不是对全局作用域的变量进行引用)那么内部函数就被称为闭包。

def fun1(x):
	def fun2(y):
		return (x*y)
	return fun2
i=fun1(5)
print(type(i))

<class 'function'>	#输出

fun1()函数返回的是对象fun2,该对象代表着该函数,所以函数类型是function。

def fun1():
	x=5
	def fun2():
		x=10
		return x
	return fun2()
i=fun1()
print(type(i))

<class 'int'>	#输出

fun1()函数的返回值是函数fun2(),然后会继续执行函数fun2(),而函数fun2()的返回值是整型x,所以函数类型为整型。

def fun1():
	x=5
	def fun2():
		x*=x
		return x
	return fun2()
i=fun1()
print(i)

#错误提示
UnboundLocalError: local variable 'x' referenced before assignment

在该程序中,x在fun2()的外部,对于fun2()函数,x相似于全局变量,那么它们的关系就想全局变量和局部变量一样,所以我们也是无法在函数fun2()内修改x。
但我们可以通过关键字nonlocal来改变x:

def fun1():
	x=5
	def fun2():
		nonlocal x
		x*=x
		return x
	return fun2()
i=fun1()
print(i)

25	#输出
发布了14 篇原创文章 · 获赞 0 · 访问量 294

猜你喜欢

转载自blog.csdn.net/lhyhaiyan/article/details/104383876