用于functools.partial()
部分应用函数:
from functools import partial
TRANSFORM_PIPELINE = [
partial(do_xslt, 'pass1.xsl'),
partial(do_xslt, 'pass2.xsl'),
partial(do_xslt, 'pass3.xsl')
]
调用返回的函数partial()
将调用do_xslt('pass1.xsl', *args, **kwargs)
并作为传递给新函数的参数*args
。**kwargs
演示:
>>> def do_xslt(xsl, xml):
... print 'do_xslt(%r, %r)' % (xsl, xml)
... return xml + '*' + xsl
...
>>> from functools import partial
>>> TRANSFORM_PIPELINE = [
... partial(do_xslt, 'pass1.xsl'),
... partial(do_xslt, 'pass2.xsl'),
... partial(do_xslt, 'pass3.xsl')
... ]
>>> x = 'xml is lame'
>>> for transform in TRANSFORM_PIPELINE:
... x = transform(x)
... print x
...
do_xslt('pass1.xsl', 'xml is lame')
xml is lame*pass1.xsl
do_xslt('pass2.xsl', 'xml is lame*pass1.xsl')
xml is lame*pass1.xsl*pass2.xsl
do_xslt('pass3.xsl', 'xml is lame*pass1.xsl*pass2.xsl')
xml is lame*pass1.xsl*pass2.xsl*pass3.xsl