有什么方法能让通过引用来改变变量吗?


    参数是通过assignment来传递的.原因是双重的:

    • 传递的参数实际上是一个对象的引用(但是这个引用是通过值传递的)
    • 一些数据类型是可变的,但有一些就不是.
      所以:

    • 如果传递一个可变对象到一个方法,方法就会获得那个对象的引用,而你也可以随心所欲的改变它了.但是你在方法里重新绑定了这个引用,外部是无法得知的,而当函数完成后,外界的引用依然指向原来的对象.

    • 如果你传递一个不可变的对象到一个方法,你仍然不能在外边重新绑定引用,你连改变对象都不可以.
      为了弄懂,来几个例子.

    让我们试着修改当做参数传递给方法的列表:

    1. def try_to_change_list_contents(the_list):
    2. print 'got', the_list
    3. the_list.append('four')
    4. print 'changed to', the_list
    5. outer_list = ['one', 'two', 'three']
    6. print 'before, outer_list =', outer_list
    7. try_to_change_list_contents(outer_list)

    输出:

    1. before, outer_list = ['one', 'two', 'three']
    2. got ['one', 'two', 'three']
    3. changed to ['one', 'two', 'three', 'four']
    4. after, outer_list = ['one', 'two', 'three', 'four']

    现在让我们来看看我们试着改变作为传递参数的引用时到底发生了什么:

    输出:

    1. before, outer_list = ['we', 'like', 'proper', 'English']
    2. got ['we', 'like', 'proper', 'English']
    3. after, outer_list = ['we', 'like', 'proper', 'English']

    既然the_list参数是通过值进行传递的,那么为它赋值将会对方法以外没有影响.the_listouter_list引用(注意,名词)的一个拷贝,我们将the_list指向一个新的列表,但是并没有改变outer_list的指向.

    它是不可变类型,所以我们不能改变字符串里的内容.

    现在,让我们试着改变引用

    1. def try_to_change_string_reference(the_string):
    2. print 'got', the_string
    3. the_string = 'In a kingdom by the sea'
    4. print 'set to', the_string
    5. outer_string = 'It was many and many a year ago'
    6. print 'before, outer_string =', outer_string
    7. print 'after, outer_string =', outer_string

    输出:

    希望你清楚以上那些.

    修改:到现在位置还没有回答"有什么方法同过引用传递变量?",让我们往下看.

    你可以返回一个新值.这不会改变传过来的值,但是能得到你想要的结果.

    1. def return_a_whole_new_string(the_string):
    2. new_string = something_to_do_with_the_old_string(the_string)
    3. return new_string
    4. # 你可以像这样调用
    5. my_string = return_a_whole_new_string(my_string)

    如果你真的不想用一个返回值,你可以建一个存放你的值的类,然后把它传递给函数或者用一个已有的类,像列表:

    1. def use_a_wrapper_to_simulate_pass_by_reference(stuff_to_change):
    2. new_string = something_to_do_with_the_old_string(stuff_to_change[0])
    3. stuff_to_change[0] = new_string
    4. # 你可以像这样调用
    5. wrapper = [my_string]
    6. use_a_wrapper_to_simulate_pass_by_reference(wrapper)

    虽然看起来有一点笨重,但还是达到你的效果了.