参数是通过分配 http://docs.python.org/3/faq/programming.html#how-do-i-write-a-function-with-output-parameters-call-by-reference。这背后的理由有两个:
- 传入的参数实际上是一个参考到一个对象(但引用是按值传递的)
- 某些数据类型是可变的,但其他数据类型则不然
So:
为了更清楚地说明这一点,让我们举一些例子。
列表 - 可变类型
让我们尝试修改传递给方法的列表:
def try_to_change_list_contents(the_list):
print('got', the_list)
the_list.append('four')
print('changed to', the_list)
outer_list = ['one', 'two', 'three']
print('before, outer_list =', outer_list)
try_to_change_list_contents(outer_list)
print('after, outer_list =', outer_list)
Output:
before, outer_list = ['one', 'two', 'three']
got ['one', 'two', 'three']
changed to ['one', 'two', 'three', 'four']
after, outer_list = ['one', 'two', 'three', 'four']
由于传入的参数是对的引用outer_list
,而不是它的副本,我们可以使用变异列表方法来更改它,并将更改反映在外部范围中。
现在让我们看看当我们尝试更改作为参数传入的引用时会发生什么:
def try_to_change_list_reference(the_list):
print('got', the_list)
the_list = ['and', 'we', 'can', 'not', 'lie']
print('set to', the_list)
outer_list = ['we', 'like', 'proper', 'English']
print('before, outer_list =', outer_list)
try_to_change_list_reference(outer_list)
print('after, outer_list =', outer_list)
Output:
before, outer_list = ['we', 'like', 'proper', 'English']
got ['we', 'like', 'proper', 'English']
set to ['and', 'we', 'can', 'not', 'lie']
after, outer_list = ['we', 'like', 'proper', 'English']
自从the_list
参数是按值传递的,为其分配一个新列表对于方法外部的代码可以看到没有任何影响。这the_list
是一个副本outer_list
参考,我们有the_list
指向一个新列表,但无法更改位置outer_list
尖。
字符串 - 不可变类型
它是不可变的,因此我们无法更改字符串的内容
现在,让我们尝试更改参考
def try_to_change_string_reference(the_string):
print('got', the_string)
the_string = 'In a kingdom by the sea'
print('set to', the_string)
outer_string = 'It was many and many a year ago'
print('before, outer_string =', outer_string)
try_to_change_string_reference(outer_string)
print('after, outer_string =', outer_string)
Output:
before, outer_string = It was many and many a year ago
got It was many and many a year ago
set to In a kingdom by the sea
after, outer_string = It was many and many a year ago
再次强调,自从the_string
参数是按值传递的,为其分配新字符串不会对方法外部的代码可见产生任何影响。这the_string
是一个副本outer_string
参考,我们有the_string
指向一个新字符串,但无法更改位置outer_string
尖。
我希望这能让事情澄清一点。
EDIT:值得注意的是,这并没有回答@David 最初提出的问题:“我可以做些什么来通过实际引用传递变量吗?”。让我们努力吧。
我们如何解决这个问题?
正如@Andrea的回答所示,您可以返回新值。这不会改变传入内容的方式,但可以让您获取所需的信息:
def return_a_whole_new_string(the_string):
new_string = something_to_do_with_the_old_string(the_string)
return new_string
# then you could call it like
my_string = return_a_whole_new_string(my_string)
如果您确实想避免使用返回值,您可以创建一个类来保存您的值并将其传递给函数或使用现有的类,例如列表:
def use_a_wrapper_to_simulate_pass_by_reference(stuff_to_change):
new_string = something_to_do_with_the_old_string(stuff_to_change[0])
stuff_to_change[0] = new_string
# then you could call it like
wrapper = [my_string]
use_a_wrapper_to_simulate_pass_by_reference(wrapper)
do_something_with(wrapper[0])
虽然这看起来有点麻烦。