在某些方面,Python 中的所有调用都是通过引用调用的。事实上,所有变量在某种意义上都是引用。但是某些类型,例如您示例中的int,无法更改。
例如,list,您正在寻找的功能是微不足道的:
def change_it(some_list):
some_list.append("world")
foo = ["hello"]
change_it(foo)
print(foo) # prints ['hello', 'world']
但是,请注意,重新分配 参数 变量 some_list 不会更改调用上下文中的值。
不过,如果您问这个问题,您可能希望使用一个函数设置两个或三个变量。在这种情况下,您正在寻找这样的东西:
def foo_bar(x, y, z):
return 2*x, 3*y, 4*z
x = 3
y = 4
z = 5
x, y, z = foo_bar(x, y, z)
print(y) # prints 12
当然,您可以在 Python 中做任何事情,但这并不意味着您应该这样做。按照电视节目 Mythbusters 的风格,这里有一些东西可以满足您的需求
import inspect
def foo(bar):
frame = inspect.currentframe()
outer = inspect.getouterframes(frame)[1][0]
outer.f_locals[bar] = 2 * outer.f_locals[bar]
a = 15
foo("a")
print(a) # prints 30
甚至更糟:
import inspect
import re
def foo(bar):
# get the current call stack
my_stack = inspect.stack()
# get the outer frame object off of the stack
outer = my_stack[1][0]
# get the calling line of code; see the inspect module documentation
# only works if the call is not split across multiple lines of code
calling_line = my_stack[1][4][0]
# get this function's name
my_name = my_stack[0][3]
# do a regular expression search for the function call in traditional form
# and extract the name of the first parameter
m = re.search(my_name + "\s*\(\s*(\w+)\s*\)", calling_line)
if m:
# finally, set the variable in the outer context
outer.f_locals[m.group(1)] = 2 * outer.f_locals[m.group(1)]
else:
raise TypeError("Non-traditional function call. Why don't you just"
" give up on pass-by-reference already?")
# now this works like you would expect
a = 15
foo(a)
print(a)
# but then this doesn't work:
baz = foo_bar
baz(a) # raises TypeError
# and this *really*, disastrously doesn't work
a, b = 15, 20
foo_bar, baz = str, foo_bar
baz(b) and foo_bar(a)
print(a, b) # prints 30, 20
拜托,拜托,拜托,不要这样做。我把它放在这里只是为了激发读者去研究 Python 中一些比较晦涩的部分。