python - Comment passer une variable par référence

Mots clés : pythonreferenceparameter-passingpass-by-referencepython

meilleur 3 Réponses python - Comment passer une variable par référence

vote vote

95

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'] 
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'] 
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 
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]) 
vote vote

87

a = 1 a = 2 
def __init__(self):     self.variable = 'Original'     self.Change(self.variable)  def Change(self, var):     var = 'Changed' 
def __init__(self):              self.variable = ['Original']     self.Change(self.variable)  def Change(self, var):     var[0] = 'Changed' 
vote vote

75

a = [1, 2, 3] b = a b.append(4) b = ['a', 'b'] print a, b      # prints [1, 2, 3, 4] ['a', 'b'] 

Questions similaires