我用封闭代替,没有副作用.
这是一个例子(我刚刚修改了Felix Klings answer的原始示例):
def replaceNthWith(n, replacement):
c = [0]
def replace(match):
c[0] += 1
return replacement if c[0] == n else match.group(0)
return replace
用法:
# reset state (in our case count, c=0) for each string manipulation
re.sub(pattern, replaceNthWith(n, replacement), str1)
re.sub(pattern, replaceNthWith(n, replacement), str2)
#or persist state between calls
replace = replaceNthWith(n, replacement)
re.sub(pattern, replace, str1)
re.sub(pattern, replace, str2)
对于可变的,如果有人调用replace(match,c = [])会发生什么?
对于属性你破坏了封装(是的,我知道python没有在类中实现差异原因……)