内置高阶函数:
from common.iterable_tools import IterableHelper
class Employee:
def __init__(self, eid, did, name, money):
self.eid = eid # 员工编号
self.did = did # 部门编号
self.name = name
self.money = money
# 员工列表
list_employees = [
Employee(1001, 9002, "师父", 60000),
Employee(1002, 9001, "孙悟空", 50000),
Employee(1003, 9002, "猪八戒", 20000),
Employee(1004, 9001, "沙僧", 30000),
Employee(1005, 9001, "小白龙", 15000),
]
# 需求:工资大于2w
# for item in IterableHelper.find_all(list_employees,lambda emp:emp.money > 20000):
# print(item.__dict__)
# 1.过滤
for item in filter(lambda emp: emp.money > 20000, list_employees):
print(item.__dict__)
# 需求:查找所有员工姓名
# for item in IterableHelper.select(list_employees,lambda emp:emp.name):
# print(item)
# 2. 映射
for item in map(lambda emp: emp.name, list_employees):
print(item)
# 3. 最值
# 需求:获取最富
emp = max(list_employees, key=lambda emp: emp.money)
print(emp.__dict__)
# 需求:获取最穷
emp = min(list_employees, key=lambda emp: emp.money)
print(emp.__dict__)
# 4. 排序
# 需求:根据部门编号排序(升序)
list_result = sorted(list_employees,key =lambda emp: emp.did )
for item in list_result:
print(item.__dict__)
# 需求:根据部门编号排序(降序)
list_result = sorted(list_employees,key =lambda emp: emp.did,reverse=True)
for item in list_result:
print(item.__dict__)
enclosing:外部嵌套作用域:函数嵌套
外部嵌套变量:内函数可以读取外部嵌套变量
如果修改必须通过nonlocal声明
# 复习
b = 20 # 全局变量
def func01():
a = 10 # 局部变量
global b
b = 200
def func02():
c = 30# 局部变量 外部嵌套变量
def func03():
nonlocal c
c = 300
func03()
print(c)
func02()
闭包:
三大要素:. 有内有外
. 内使用外
. 外返回内
字面意思:封闭内存的空间
价值:外部函数执行后,栈帧不释放
def func01(): # 中午饭
data = 10 # 剩菜
def func02(): # 晚饭
print(data) # 继续吃剩菜
return func02
# 调用外部函数,得到内部函数
result = func01()
# 调用内部函数
result()
def give_gife_money(money):
print("获得", money, "元压岁钱")
def child_buy(commodity, price):
nonlocal money
money -= price
print("购买了", commodity, "花了", price, "还剩下", money)
return child_buy
action = give_gife_money(1000)
action("遥控飞机", 300)
action("糖", 100)
action("房", 500)
# 练习:使用闭包模拟以下情景:
# 在银行开户存入10000
# 购买xx商品花了xx元
# 购买xx商品花了xx元
装饰器:闭包
有外有内(得到1000元):外部函数接收旧功能,内部函数负责包裹新旧功能
内访问外(用1000元购买商品):同时执行新旧功能
外访问内(返回购买行为,才能够不断购买):不断执行新旧功能
def new_func(func):
def wrapper():
# 执行
print("新功能")
func()
return wrapper
def func01():
print("功能1")
# func02 = new_func(func02)
@new_func# 执行外部函数
def func02():
print("功能2")
# 旧功能 = 新功能 + 旧功能
# func01 = new_func + func01
# 调用外部函数,得到内部函数
func01 = new_func(func01)
# 不断调用内部函数
func01()
func02()
装饰器:
def new_func(func):
def wrapper(*args,**kwargs):# 将多个实参合为一个容器
print("新功能")
res = func(*args,**kwargs) # 一个容器拆为多个形参
return res # 将内部函数的返回值设置为旧功能的返回值
return wrapper
@new_func
def func01(p1):
print("功能1")
return 1
@new_func
def func02(p1,p2):
print("功能2")
return 2
print(func01(10)) # 调用内部函数wrapper 1
print(func02(20,30)) # 2
print(func02(20,p2 = 30)) # 2