Quantcast
Channel: CodeSection,代码区,Python开发技术文章_教程 - CodeSec
Viewing all articles
Browse latest Browse all 9596

Python-闭包

$
0
0
1.闭包的概念

闭包是一个包含有环境变量取值的函数对象,是一种组织代码的结构,闭包的功能在于,它提高了代码的可重用性。

2.闭包的使用

关于闭包是什么样的形式,又是如何使用的,我们来看几段代码;

code1:

def line_func(): def line(x): return 5*x + 1 return line #返回函数对象 line_hl = line_func() print(line_hl(3))

打印结果:16

code2:

def line_func(): b = 6 def line(x): return 5*x + b return line b = 20 line_hl = line_func() print(line_hl(3))

打印结果:21

code3:

def line_func(): b = 6 def line(x): return 5*x + b return line b = 20; line_hl = line_func() print(line_hl.__closure__) #line_hl的闭包属性,是一个tuple print(line_hl.__closure__[0].cell_contents) #line_hl的闭包的第1个元素,也就是函数中定义的b,即闭包中的环境变量;

打印结果:

(,)

6

code4:

def line_func(a, b): def line(x): return a*x + b return line line_hl_1 = line_func(2,3) line_hl_2 = line_func(6,1) print(line_hl_1(3), line_hl_2(3))

打印结果:(9, 19)

通过上述代码,可以发现,我们在定义和计算一条直线时,只需传入两个参数,而无需传入三个,这样就大大提高了代码的可重复利用性。


Viewing all articles
Browse latest Browse all 9596

Latest Images

Trending Articles