def func(): a = 1 b = 2 return a+b def sum(a): def add(b): return a+b return add num1 = func() num2 = sum(2) print(type(num1)) print(type(num2)) print(num2(8))demo2:
def counter():
cnt = [0]
def add_one():
cnt[0] += 1
return cnt[0]
return add_one
num1 = counter()
print(num1())
print(num1())
print(num1())
print("\n")
def counter(FIRST=5):
cnt = [FIRST]
def add_one():
cnt[0] += 1
return cnt[0]
return add_one
num5 = counter(5)
print(num5())
print(num5())
闭包的使用
#计算一次函数 y = a*x + b
#不用闭包的写法
def a_line(a,b,x):
return a*x + b
#采用 lambda 的写法
def a_line(a,b):
return lambda x: a*x + b
line1=a_line(3,5)
print(line1(10))
#用闭包的写法
def a_line(a,b):
def arg_y(x):
return a*x + b
return arg_y
line1 = a_line(3,5)
print(line1(10))
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)