【发布时间】:2020-11-12 02:18:51
【问题描述】:
例如:
x = {'a':1, 'b':2}
y = {}
# only requirement: x and y has to be parameters of function foo
def foo(x,y):
'''
How do I switch the two variables inside this function without scope issues?
'''
print('x =', x)
print('y =', y)
结果:
x = {}
y = {'a':1, 'b':2}
我尝试将 global x, y 和 x,y = y,x 放入函数中,但由于它们已经是全局的,所以得到了预期的错误:
SyntaxError: name 'x' is parameter and global
# Same thing happens for y
【问题讨论】:
-
重命名参数,不要使用
x,y,因为它已经代表全局变量 -
x 和 y 必须是函数 foo 的参数,抱歉忘了提。
-
我的意思是你可以将
x,y重命名为其他名称,并不是要删除它们,不要让参数名称与全局变量相同,因为它会引发@987654330 @
标签: python variables global-variables