您可以使用functools.partial
:
>>> from functools import partial
>>> def foo(x, y):
... print x+y
...
>>> partial(foo, y=3)
<functools.partial object at 0xb7209f54>
>>> f = partial(foo, y=3)
>>> f(2)
5
在您的例子:
def function(x, y):
pass # ...
r.sub(functools.partial(function, y=arg),string)
和一個真正的使用正則表達式有:
>>> s = "the quick brown fox jumps over the lazy dog"
>>> def capitalize_long(match, length):
... word = match.group(0)
... return word.capitalize() if len(word) > length else word
...
>>> r = re.compile('\w+')
>>> r.sub(partial(capitalize_long, length=3), s)
'the Quick Brown fox Jumps Over the Lazy dog'
啊謝謝!幾乎與lambda相同:]這會是更接近它的「pythonic」方式嗎? – Stoof
@Stefan我的觀點是,大多數Python大師會考慮部分更pythonic,雖然它可以是相當主觀的。 – brandizzi