Python学习笔记六_函数闭包

Python学习笔记六_函数闭包

闭包定义

闭包: 在函数嵌套的情况下,内部函数使用了外部函数的参数或者变量,并且把这个内部函数返回,这个内部函数可以成为闭包(对应得到就是一个函数)

举例说明:

# NO.1
def line_conf(a, b):
	def line(x):
		return a * x + b
	return line
    
# NO.2
def line_conf():
	a = 1
	b = 2
 
	def line(x):
		print(a * x + b)
	return line
 
# NO.3
def _line_(a,b):
	def line_c(c):
		def line(x):
			return a*(x**2)+b*x+c
		return line
	return line_c

闭包形成的条件

  1. 要有内嵌函数
  2. 内部函数使用外部函数的变量和参数
  3. 外部函数返回内嵌函数

作用:提高代码的复用性

举例说明:

def line_conf(a, b):
	def line(x):
		return a * x + b
	return line

#根据条件生成不同的函数
line1 = line_conf(1,1)
y1 = line1(10)
line2 = line_conf(10,1)
y2 = line2(10)

print(y1,y2)

输出结果:

11 101
Process finished with exit code 0

猜你喜欢

转载自blog.csdn.net/weixin_43817580/article/details/86777508
今日推荐