我正在尝试在 python 中编写一个类对象,它的属性是能够修改私有(private)字符串的闭包函数,我在很大程度上理解闭包,但我无法让它与多个闭包一起工作。我试图返回一个函数数组,但我得到了
local variable 'string' referenced before assignment
向我表明字符串变量已被销毁或函数未保留其关闭状态且无法访问它。 get_val 函数似乎有效,我尝试添加全局声明,但这不是问题所在,或者我无法使其正常工作。
class StringUpdater:
def _(self):
string = "MI"
def get_val():
return string
def add_u():
if string.endswith("I"):
string+="U"
def add_two_through_last():
string+=string[1:]
def replace_III_with_U():
#global string
string.replace("III", "U")
def remove_UU():
#global string
string.replace("UU", "")
return [get_val,add_u,add_two_through_last,replace_III_with_U,remove_UU]
def __init__(self):
str_obj = self._()
self.get_val = str_obj[0]
self.add_u = str_obj[1]
self.add_two_through_last = str_obj[2]
self.replace_III_with_U = str_obj[3]
self.remove_UU = str_obj[4]
f = StringUpdater()
print f.add_two_through_last()
print f.get_val()
请您参考如下方法:
你收到错误 string referenced before assignment 的原因是你在 add_u 中试图写入一个名为 string 的变量通过 += 运算符,因此 Python 在 add_u 中创建了一个新的局部变量,它不同于 _ 中的变量。
这可以通过 Python 3 中的 nonlocal 来解决,但如果你坚持使用 Python 2,我会把“外部”string 包装在一个数组中。我会说这是在 Python 中使用的一种相当常见的模式,但大多数时候 Python 并没有真正以函数式方式使用,尽管它完全能够实现闭包。
为了展示这是如何工作的,我稍微简化了一些事情并放弃了 class,制作了一个使用封闭字符串的函数字典。为了写入那个字符串,我把它放在一个数组中:
def _mu():
data = ["MI"]
def rule1():
if data[0].endswith('I'): data[0] += 'U'
def rule2():
data[0] += data[0][1:]
def rule3():
data[0] = data[0].replace('III', 'U')
def rule4():
data[0] = data[0].replace('UU', '')
return {
'value': lambda: data[0],
'rule1': rule1,
'rule2': rule2,
'rule3': rule3,
'rule4': rule4}
mu = _mu()
我称它为 mu 因为这些规则可以识别为 MU-Puzzle .
现在你可以写:
mu['value']() # => 'MI'
mu['rule1']()
mu['value']() # => 'MIU'
