业务逻辑开发,未考虑太多封装性>>---->>包、类库的开发
函数式编程
闭包:函数+定义时函数外部的环境变量(若内部有被局部变量赋值覆盖,不再认为是闭包,__closure__为None)
def curve_pre():
a = 25
def curve(x):
return a*x*x
return curve
f = curve_pre()
print(f(2))
print(f.__closure__[0].cell_contents) # 一起返回环境变量的位置
#
旅行者,计算路径长度,x=0,起点,每次走不定步数;
# 1---全局变量没有自封性
origin = 0
def go(step):
global origin
new_step = origin + step
origin = new_step
return new_step
print(go(2)) # 2
print(go(3)) # 5
print(go(6)) # 11
# 2---全局变量没有自封性
origin = 0
def factory():
def go(step):
global origin
new_step = origin + step
origin = new_step
return new_step
return go
f = factory()
print(f(2))
print(f(5))
# 3-----所有操作在函数内部
origin = 0
def factory(pos):
def go(step):
nonlocal pos
new_step = pos + step
pos = new_step
return pos
return go
f = factory(origin)
print(f(2))
print(f(5))
匿名函数:lambda
def f(x,y):
return x+y
add(1,2)
f = lambda x,y: x+y
f(1,2)
map类:参数:函数,序列
list_x = [1,2,3,4,5,6,7,8,9]
r = map(lambda x: x*x,list_x)
reduce:里面的函数必须要2个参数;连续计算,连续调用
from functools import reduce
r = reduce(lambda x,y: x+y,list_x,10) # 第三个参数:10作为初始值
print(r)
谷歌提出的大数据计算模型:map/reduce 编程模型 映射/归约 主要用作并行计算;函数式编程
filter:过滤;返回值必须为可以判断为真假
list_x = [1,0,1,0,0,1]
r = filter(lambda x: True if x==1 else False, list_x)
r = filter(lambda x: x, list_x)
print(list(r))
命令式编程流程本质:
def
if else
for
函数式编程:
map reduce filter
lambda # 算子
装饰器:开闭原则:拒绝修改,可扩展
# 改变了f1()内部实现
import time
def f1():
print(time.time()) # unix时间戳,格林威治时间1970年01月01日00:00:00秒至当前总秒数
print('This is a function')
f1()
# 不使用装饰器;缺点是没有关联性
def print_current_time(func):
print(time.time())
func()
def f1():
print('This is a fucntion')
print_current_time(f1)
# 装饰器本质:
def decorator(func):
def wrapper():
print(time.time())
func()
return wrapper
def f1():
print('This is a fucntion')
f = decorator(f1)
f()
# 装饰器语法糖:
def decorator(func):
def wrapper(*args,**kw): # 可变参数;key word关键字传参
print(time.time())
func(*args,**kw)
return wrapper
@decorator
def f1():
print('This is a fucntion')
@decorator
def f2(func_name1,func_name2):
pass
f1()
# 关键字传参
@decorator
def f3(name1,name2,**kw):
print('name1'+name1)
print('name2'+name2)
print(kw)
f3('test1','test2',a=1,b=2,c=3) # ...{'a':1,'b':2..}
# 保持原有函数名不变
from functools import wraps
def decorator(func):
@wraps(func)
def wrapper():...
@decorator
def f1():
...
help(f1)
【Python3】进阶
于 2023-05-08 15:28:07 首次发布