Python functools常用函数

partial函数(偏函数)

    把一个函数的某些参数设为默认值,返回一个新函数,调用这个新函数,会更简单、

import functools
def showargs(*args,**kwargs):
    print(args)
    print(kwargs)

p1 = functools.partial(showargs,1,2,3)
p1()
p1(2,3,4)
p1(a='a',b='b')
p2 = functools.partial(showargs,a=1,b=2,c=3)
p2()

输出:

(1, 2, 3)
{}
(1, 2, 3, 2, 3, 4)
{}
(1, 2, 3)
{'a': 'a', 'b': 'b'}
()
{'a': 1, 'b': 2, 'c': 3}

wraps函数

    使用装饰器时,被装饰后的函数已经是另外一个函数了(函数名等函数属性会改变),wraps的装饰器可以消除这样的副作用

import functools

def note(func):
    "note function"
    @functools.wraps(func)
    def wapper():
        "wapper function"
        print("note something")
        return func()
    return wapper

@note
def test():
    "test function"
    print("I'm test")

test()
print(test.__doc__)

'''
输出:
note something
I'm test
test function
'''

猜你喜欢

转载自blog.csdn.net/mr_quiet/article/details/81034182