例如:
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
如果使用全局变量,请不要使用args;-(
def foo():
global x,y
x,y = y,x
对我的替代想法的启示
def foo(x,y):
return [y,x]
myList = foo(x,y)
x,y = myList[0], myList[1]
x = {'a':1, 'b':2}
y = {}
def foo():
global x,y #bring global variable in func scope
x,y = y,x #swaps variable variable values
def foo1():
globals()['x'] = {'a':1, 'b':2} #update value of global variable in func
globals()['y'] = {}
#method1
foo()
print(x,y)
#method2
x = {'a':1, 'b':2}
y = {}
foo1()
print(x,y)
这两个功能都将起作用。
如果要将变量作为args发送:检查Python关于变量可变性的概念。另外检查此