有一种方法可以通过在本地符号表中重写它来修改不可变的变量,但是,我认为它不是很好,应该尽可能避免。
另一种方式,甚至更少pythonic,是使用exec格式化指令。它得到的变量名的字符串感谢this solution为:不出所料
def getname(obj, callingLocals=locals()):
"""
a quick function to print the name of input and value.
If not for the default-Valued callingLocals, the function would always
get the name as "obj", which is not what I want.
"""
return next(k for k, v in callingLocals.items() if v is obj)
def updatevar2(k, v, callingLocals=locals()):
n = getname(k, callingLocals)
exec('global {};{}={}'.format(n, n, repr(v)))
结果:
var = "some_string"
updatevar(var, "modified_string")
print(var) # outputs "modified_string"
updatevar2(var, var + '2')
print(var) # outputs "modified_string2"
以我的经验,最好是避免这样的副作用。而是返回值(如第一个示例中所示)。如果有多个值,它们可能会像Tuple一样包装复合类型(然后由调用者分解)。另外,也许问题是“太多重复任务”?考虑:'print another_func(some_func(“some_string”))' – 2011-06-17 23:36:52
[Python:我如何通过引用传递变量?](http://stackoverflow.com/questions/986006/python-how-do- i-pass-a-by-reference) –
'x = func(x)'看起来比'modify(x,func)'糟糕吗?我完全清楚第一个例子应该做什么,0%清楚第二个应该做什么。 –