1.高阶函数
(1)接收一个或多个函数对象作为参数
(2)将函数作为返回值返回
#满足第一个条件,接收一个或者多个函数对象作为参数,但没有将函数作为返回值返回,不属于高阶函数
def fun2(n):
if n % 2 == 0:
return True
def fun1(fn):
list2 = []
for i in list1:
if fn(i):
list2.append(i)
return list2
print(fun1(fun2))
2.匿名函数
定义:没有名字的函数,无需指定函数的名字
写法:(lambda 参数:表达式) (传参)
# #匿名函数不属于高阶函数
#以下是匿名函数两张相同写法
print('-------1-------')
res = lambda a,b:a+b
print(res(1,2))
print('-------2-------')
res = (lambda a,b:a+b)(1,2)
print(res)
3.filter()函数
作用:过滤。
传递两个参数:函数对象,列表名称。
list1 = [1,2,3,4,5,6,7,8,9,10] #全局变量
def fun2(n):
if n % 2 == 0:
return True #为了过滤
print(list(filter(fun2, list1)))
4.闭包
(1)在一个外函数中定义了一个内函数。
(2)内函数中运用了外函数的临时变量。
(3)外函数的返回值是内函数的对象.
#闭包函数的实例
# outer是外部函数 a和b都是外函数的临时变量
def outer( a ):
b = 10
# inner是内函数
def inner():
#在内函数中 用到了外函数的临时变量
print(a+b)
# 外函数的返回值是内函数的引用
return inner
if __name__ == '__main__':
# 在这里我们调用外函数传入参数5
#此时外函数两个临时变量 a是5 b是10 ,并创建了内函数,然后把内函数的引用返回存给了demo
# 外函数结束的时候发现内部函数将会用到自己的临时变量,这两个临时变量就不会释放,会绑定给这个内部函数
demo = outer(5)
# 我们调用内部函数,看一看内部函数是不是能使用外部函数的临时变量
# demo存了外函数的返回值,也就是inner函数的引用,这里相当于执行inner函数
demo() # 15
demo2 = outer(7)
demo2()#17
闭包的好处:
(1)通过闭包可以创建一些只有当前函数能访问的变量。
(2)可以将一些私有数据藏到闭包中
5.装饰器
装饰器是一个特殊的闭包,符合闭包的三大构成条件。
(通过举例详细说明)
#通用装饰器
def fun_out(fn): #传一个函数进去,返回另一个闭包,接下来可以直接调用函数内这个闭包
def fun_inner(*args,**kwargs):
print("函数开始执行")
r = fn(*args,**kwargs)
print("函数执行结束")
return r
return fun_inner
def add(a,b):
return a + b
f = fun_out(add)
res = f(1, 2)
print(res)
print('-------------')
@fun_out #装饰器语法糖的写法,实际上是在def add(a,b)后,执行add = fun_out(add)
def add(a,b):
return a + b
r = add(1,2)
print(r)
print('-------------')
@fun_out #装饰器语法糖的写法 qiuji = fun_out(qiuji)
def qiuji():
print(111)
r = qiuji()
#语法糖:@fun_out 等价于fun_out(add)
def a_new_decorator(a_func):
def wrapTheFunction():
print("I am doing some boring work before executing a_func()")
a_func()
print("I am doing some boring work after executing a_func()")
return wrapTheFunction
def a_function_requiring_decoration():
print("I am the function which needs some decoration to remove my foul smell")
a_function_requiring_decoration()
a_function_requiring_decoration = a_new_decorator(a_function_requiring_decoration) #将wrapTheFunction函数作为对象传给a_function_requiring_decoration
# a_function_requiring_decoration() #调用a_function_requiring_decoration()函数
@a_new_decorator
def a_function_requiring_decoration():
print("I am the function which needs some decoration to remove my foul smell")
a_function_requiring_decoration()
print("I am the function which needs some decoration to remove my foul smell")
def logit(func):
@wraps(func)
def with_logging(*args, **kwargs):
print(func.__name__ + " was called")
return func(*args, **kwargs)
return with_logging
@logit #addition_func = logit(addition_func)
def addition_func(x):
"""Do some math."""
return x + x
print(1)
result = addition_func(4)
print(result)
from functools import wraps
def logit(func):
@wraps(func)
def logging_decorator(func):
# print(1)
@wraps(func)
def wrapped_function(*args, **kwargs):
# print(2)
log_string = func.__name__ + " was called"
print(log_string)
print(*args)
# 打开logfile,并写入内容
# with open(logfile, 'a') as opened_file:
# # 现在将日志打到指定的logfile
# opened_file.write(log_string + '\n')
# return func(*args, **kwargs)
return func()
return wrapped_function
return logging_decorator
# @logit() #myfunc1 = logit(myfunc1)
def myfunc1(a):
return 1
def myfunc2():
return 2
def myfunc3(a):
return 3
myfunc1 = logit(myfunc1) #将闭包函数对象传给myfunc1
myfunc1 = myfunc1(myfunc2) #将嵌套的闭包函数对象传给myfunc1
print(myfunc1(1))
#日志
from functools import wraps
def logit(func):
@wraps(func)
def with_logging(*args, **kwargs):
print(func.__name__ + " was called")
return func(*args, **kwargs)
return with_logging
@logit
def addition_func(x):
"""Do some math."""
return x + x
result = addition_func(4)
#在函数中嵌入装饰器,创建一个包裹函数,指定一个用于输出的日志文件。
from functools import wraps
def logit(logfile='out.log'):
def logging_decorator(func):
@wraps(func)
def wrapped_function(*args, **kwargs):
log_string = func.__name__ + " was called"
print(log_string)
# 打开logfile,并写入内容
with open(logfile, 'a') as opened_file:
# 现在将日志打到指定的logfile
opened_file.write(log_string + '\n')
return func(*args, **kwargs)
return wrapped_function
return logging_decorator
@logit()
def myfunc1():
pass
myfunc1()
6.装饰器的使用:
通过装饰器,可以在不修改原来函数的情况下来对函数进行扩展。
在开发中,我们都是通过装饰器来扩展函数的功能的。
作业:
两种写法,一种普通,一种是多嵌套一层。
#普通。
import time
def task(fn):
def task1(fn,n):
start_time = time.time()
fn(n)
end_time = time.time()
res = end_time - start_time
def print_num():
print(res)
return print_num
return task1
@task # num = task(num)
def num1():
print(1)
pass
def num(n):
while n > 0:
time.sleep(0.1)
n += -1
num1(num,1)()
#多嵌套一层。
import time
def log1():
def task(fn):
def task1(*args,**kwargs):
start_time = time.time()
fn(*args,**kwargs)
end_time = time.time()
res = end_time - start_time
def print_num():
print(res)
return print_num()
return task1
return task
# @task # num = task(num)
@log1()
def num(n):
while n > 0:
time.sleep(0.1)
n += -1
num(1)