Python - 函数属性或可变的默认值

And*_*ark 4 python

假设您有一个需要维持某种状态的函数,并且根据该状态的不同行为.我知道实现这两种方法,其中状态完全由函数存储:

  1. 使用函数属性
  2. 使用可变的默认值

使用略微修改版本的Felix Klings回答另一个问题,这里有一个示例函数,可以使用,re.sub()以便只替换正则表达式的第三个匹配:

功能属性:

def replace(match):
    replace.c = getattr(replace, "c", 0) + 1
    return repl if replace.c == 3 else match.group(0)
Run Code Online (Sandbox Code Playgroud)

可变默认值:

def replace(match, c=[0]):
    c[0] += 1
    return repl if c[0] == 3 else match.group(0)
Run Code Online (Sandbox Code Playgroud)

对我来说,第一个看起来更干净,但我更常见的是第二个.哪个更好,为什么?

Nic*_*alu 5

我改用闭包,没有副作用。

这是示例(我刚刚修改了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
Run Code Online (Sandbox Code Playgroud)

以及用法:

 # 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)
Run Code Online (Sandbox Code Playgroud)

对于可变的,如果有人调用 replace(match, c=[]) 会发生什么?

对于属性,您破坏了封装(是的,我知道由于差异原因,python 没有在类中实现...)