闭包
def curve_pre():
a = 25
def curve(x):
return a*x*x
return curve
a = 10
# a的取值不受影响,仍取25
f = curve_pre()
print(f(2))
def f1():
a = 10
def f2():
# 此a被认为是局部变量,不再构成闭包
a = 20
return a
return f2
f = f1()
print(f.__closure__)
print(f)
# 闭包解决
origin = 0
def factory(pos):
def go(step):
nonlocal pos # 声明pos不为局部变量
new_pos = pos + step
pos = new_pos
return new_pos
return go
f = factory(origin)
print(f(2))
print(f(3))
print(f(6))
# 非闭包解决累加问题
origin = 0
def go(step):
global origin #声明origin为全局变量
new_pos = origin+step
origin = new_pos
return new_pos
print(go(2))
print(go(3))
print(go(6))
def add(x, y):
return x + y
# print(add(1, 2))
# 将函数add()使用匿名函数实现
# lambada表达式
f = lambda x, y: x+y
# print(f(1, 2))
# 三元表达式
# 格式: 条件为真时返回的结果 if 条件判断 else 条件为假时的返回结果
x = 2
y = 1
r = x if x > y else y
# print(r)
# map 映射
list_x = [1, 2, 3, 4, 5, 6, 7, 8]
def square(x):
return x * x
r = map(square, list_x)
# print(list(r))
# map 与 lambada结合
list_x = [1, 2, 3, 4, 5, 6, 7, 8]
r = map(lambda x: x*x, list_x)
# print(list(r))
list_x = [1, 2, 3, 4, 5, 6, 7, 8]
list_y = [1, 2, 3, 4, 5, 6, 7, 8]
r = map(lambda x, y: x*x+y, list_x,list_y)
#print(list(r))
# reduce
# 连续计算,连续调用lambda
from functools import reduce
list_x = [1, 2, 3, 4, 5, 6, 7, 8]
r = reduce(lambda x, y: x+y, list_x) # 上一次计算结果作为x
#print(r) # 结果为36
# filter
list_x = [1, 0, 1, 0, 0, 1]
# 剔除0 保留1
r = filter(lambda x: True if x==1 else False, list_x)
# print(list(r))
# 装饰器
import time
def decorator(func):
def wraaper(*args,**kw): # 可变参数
print(time.time())
func(*args,**kw )
return wraaper
@decorator
def f1(func_name):
print('This is a function named ' + func_name)
@decorator
def f2(func_name1, func_name2):
print('This is a function named ' + func_name1 + ','+func_name2)
@decorator
def f3(func_name1, func_name2, **kw): # 添加关键字参数
print('This is a function named ' + func_name1 + ',' + func_name2)
print(kw)
f1('test')
f2('test1', 'test2')
f3('test1', 'test2',a=1,b=2,c='123')