ython 文档似乎不清楚参数是通过引用传递还是通过值传递,以下代码生成未更改的值 ‘Original’
class PassByReference: def __init__(self): self.variable = 'Original' self.change(self.variable) print(self.variable) def change(self, var): var = 'Changed'
我可以做些什么来通过实际引用传递变量吗?
参数通过 assignment 传递。这背后的理由是双重的:
所以:
为了更清楚,让我们举一些例子。
让我们尝试修改传递给方法的列表:
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)
输出:
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,而不是它的副本,我们可以使用 mutating list 方法对其进行更改,并将更改反映在外部范围中。
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)
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指向的位置。
the_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)
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指向的位置。
the_string
outer_string
我希望这能澄清一点。
编辑:有人指出,这并没有回答@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])
虽然这看起来有点麻烦。