python常用模块-functools模块

functools模块

  functools模块里面放了很多的工具函数,此处我们只介绍常用到的两个:

  • partial函数(偏函数)绑定了一部分参数的函数。作用就是少传参数,更短,更简洁。

  • wraps函数:避免多个函数被两个装饰器装饰时就报错,因为两个函数名一样,第二个函数再去装饰的话就报错,最好是加上这个,代码更加健壮

# partial函数(偏函数) 
from functools import partial
# 案例1
def add(a, b):
 
    return a + b
 
add(1, 2)
 
3
 
plus3 = partial(add, 1)
 
plus5 = partial(add, 2)
 
plus3(2)
3
 
plus5(1)
 
3 

# 案例2
>>> partial_sorted = partial(sorted,reverse=True)
>>> partial_sorted(list1)
[123, 53, 34, 23]
    
# 案例3
def showarg(*args, **kw):
    print(args)
    print(kw)
 
>>> p1=partial(showarg, 1,2,3)
>>> p1()
(1, 2, 3)
{}

>>> p1(4,5,6)
(1, 2, 3, 4, 5, 6)
{}

>>> p1(a='python', b='itcast')
(1, 2, 3)
{'a': 'python', 'b': 'itcast'}
 
>>> p2=partial(showarg, a=3,b='linux')
>>> p2()
()
{'a': 3, 'b': 'linux'}

>>> p2(1,2)
(1, 2)
{'a': 3, 'b': 'linux'}

>>> p2(a='python', b='itcast')
()
{'a': 'python', 'b': 'itcast'}

# wraps函数:添加装饰器后由于函数名和函数的doc发生了改变,所有此方法来消除这样的副作用

def note(func):
    def wrapper(func):
        print('note something')
        return func()
    return wrapper
@note
def test():
    print('I am test')
 
test()
print(test.__doc__)
print(test.__name__)

note something
I am test
wrapper function # 这里结果就发生了改变,本来应该是test function,是因为装饰器影响的
wrapper          # 这里的name属性也被装饰器影响到了,本应该是 test
-----------------------------------------------------------------------------------------------

import functools
def note(func):
    @functools.wraps(func)
    def wrapper(func):
        print('note something')
        return func()
    return wrapper
 
@note
def test():
    print('I am test')
 
test()
print(test.__doc__)
print(test.__name__)

note something
I am test
test function # 使用@functools.wraps(func)装饰器后,这个就不会受到影响了
test

# reduce 从左到右对一个序列的项累计地应用有两个参数的函数,以此合并序列到一个单一值。
from functools import reduce
>>> reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) # 计算的就是((((1+2)+3)+4)+5)
15 

猜你喜欢

转载自www.cnblogs.com/su-sir/p/12516224.html