from functools import partial
from queue import Queue
from functools import wraps
可接受任意数量参数的函数
# 接受任意数量的位置参数,使用*defavg(first,*rest):# A tuplereturn(first +sum(rest))/(1+len(rest))# print(avg(1, 2, 3, 4, 5))# 接受任意数量的关键字参数,用**defget_item(**attr):for k, v in attr.items():# A dictprint(k, v)# get_item(a=1, b=2)
只接受关键字参数的函数
defmini(*values, clip=None):
m =min(values)if clip isnotNone:
m = clip if clip > m else m
return m
print(mini(1,5,2,-5,10))print(mini(1,5,2,-5,10, clip=0))# 指定关键字
给函数参数增加元信息
defadd(x:int, y:int)->int:return x + y
print(add.__annotations__)# 函数注解
返回多个值的函数(直接return)
defmyfun():return1,2,3# 实际上是返回元组
a, b, c= myfun()
定义有默认参数的函数
defspam(a, b=42, c=None):# 可修改容器使用Noneif c isNone:
c =[]print(a, b, c)
spam(1,25,[])
x =[1]
spam(1,25, x)
测试某个参数是不是有传递进来
_no_value =object()defspam2(a, b=_no_value):if b is _no_value:print('No b value supplied')# spam2(1)# spam2(2, None)
匿名函数捕获变量值
xx =10
fun1 =lambda y: xx + y
xx =20
fun2 =lambda y: xx + y
print(fun1(10), fun2(10))# 30 30 xx是自由变量
funcs =[lambda x: x+n for n inrange(5)]for i in funcs:print(i(0), end=' ')print()# 定义时就捕获值
xx =10
fun3 =lambda y, xx=xx: xx + y
xx =20
fun4 =lambda y, xx=xx: xx + y
print(fun3(10), fun4(10))# 20 30# funcs = [lambda x, n=n: x+n for n in range(5)]
减少可调用对象的参数个数
# functools.partial()defspam(a, b, c, d):return a, b, c, d
s1 = partial(spam,10)# a = 1
s2 = partial(spam, d=42)# d = 42
s3 = partial(spam,1,2, d=42)# a = 1, b = 2, d = 42print(s1(2,3,4))
# from queue import Queue# from functools import wraps## def apply_async(func, args, *, callback):# # Compute the result# result = func(*args)# callback(result)# def add(x, y):# return x + y# class Async:# def __init__(self, func, args):# self.func = func# self.args = args## def inlined_async(func):# @wraps(func)# def wrapper(*args):# f = func(*args)# result_queue = Queue()# result_queue.put(None)# while True:# result = result_queue.get()# try:# a = f.send(result)# apply_async(a.func, a.args, callback=result_queue.put)# except StopIteration:# break# return wrapper# @inlined_async# def test():# r = yield Async(add, (2, 3))# print(r)# r = yield Async(add, ('hello', 'world'))# print(r)# for n in range(10):# r = yield Async(add, (n, n))# print(r)# print('Goodbye')# test()
访问闭包中定义的变量
defsample():
n =0deffunc():print('n=', n)defget_n():return n
defset_n(value):nonlocal n
n = value
func.get_n = get_n
func.set_n = set_n
return func
f = sample()
f()
f.set_n(10)
f()print(f.get_n())