Pythonでpartialを使用してメソッドのデフォルトパラメータのインスタンスを変更

1592 ワード

Python標準ライブラリのfunctoolsライブラリには、メソッドに操作性のあるパッケージがたくさんあります.partial Objectsは、メソッドパラメータのデフォルト値の変更です.簡単なアプリケーションテストを見てみましょう.
 
  
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#python2.7x
#partial.py
#authror: orangleliu

'''
functools Partial
1
2
'''
def foo(a,b=0) :
    '''
    int add'
    '''
    print a + b

#user default argument
foo(1)

#change default argument once
foo(1,1)

#change function's default argument, and you can use the function with new argument
import functools

foo1 = functools.partial(foo, b=5)  #change "b" default argument
foo1(1)

foo2 = functools.partial(foo, a=10) #give "a" default argument
foo2()

'''
foo2 is a partial object,it only has three read-only attributes
i will list them
'''
print foo2.func
print foo2.args
print foo2.keywords
print dir(foo2)

## partial __name__ __doc__ , update_wrapper partial
print foo2.__doc__
'''

partial(func, *args, **keywords) - new function with partial application
    of the given arguments and keywords.
'''

functools.update_wrapper(foo2, foo)
print foo2.__doc__
'''
foo
'''