我有一个功能:
def globalrn(name, newname):
exec("""global {}""".format(name))
exec("""globals()[newname] = name""")
exec("""del {}""".format(globals()[name])) # using string as a variable name based from answers from https://stackoverflow.com/questions/37717584/how-to-use-string-value-as-a-variable-name-in-python其余的代码(不是功能的一部分).
x = 3
globalrn('x', 'y')
print(x)
print(y)我得到了一个错误:
Traceback (most recent call last):
File "rn", line 8, in <module>
globalrn('x', 'y')
File "rn", line 4, in globalrn
exec("""del {}""".format(globals()[name]))
File "<string>", line 1
SyntaxError: cannot delete literal我不知道为什么会这样。
(debian/ubuntu,python-3.8)
发布于 2021-12-21 08:11:52
如果我正确地理解了您的意思,那么您希望重命名一个全局变量:您可以更容易地这样做:globals()允许您访问字典中的所有全局变量,这样您就可以从字典中删除一个值并用不同的键插入它。
def globalrn(name, newname):
globals()[newname] = globals().pop(name)(.pop(key)用给定的key删除字典中的条目并返回其值)
https://stackoverflow.com/questions/70432272
复制相似问题