Python: functions to change values 'in place'?

前端 未结 1 438
独厮守ぢ
独厮守ぢ 2021-02-08 12:33

I\'d like to implement a function that allows the values of its arguments to be reallocated \'in place\'.

As an example, a function that will increment argument x

相关标签:
1条回答
  • 2021-02-08 12:50

    Why does your function not change the final values of X and Y ?

    In Python When a function with arguments is called, copies of the values of the arguments are stored in local variables. Indeed when you write

    def incdec(x,y,d):
        x += d
        y -= d
    

    the only thing that changes are the x and y that are IN THE function indec. But at the end of the function local variables are lost. To obtain what you want you should remember what the function did. To remember those values AFTER the function you should re-assigne x and y like this:

    def incdec(x,y,d):
        x += d
        y -= d
        return (x,y)
    
    # and then 
    
    X = 5; Y = 7; d = 2
    X,Y = incdec(X,Y,d)
    

    this works because X,Y are of type int. What you also could do is using a list to have a direct access to the variables you want to change.

    def incdec(list_1,d):
        list_1[0] += d
        list_1[1] -= d
        #no return needed
    
    # and then 
    X = 5; Y = 7; d = 2
    new_list = [X, Y]
    incdec(new_list,d) #the list has changed but not X and Y
    

    Don t get me wrong, the arguments passed are still a copy as I said earlier but when you copy a list, only references are copied, but those are still looking at the same object. Here's a demo:

    number = 5
    list_a = [number] #we copy the value of number
    print (list_a[0]) # output is 5
    list_b = list_a # we copy all references os list_a into list_b
    print(list_b[0]) # output is 5
    list_a[0]=99
    print(list_b[0]) # output is 99
    print(number)    # output is 5
    

    as you can see list_a[0] and list_b[0] is one same object but number is a different one That s because we copied the value of number and not the reference. I recommend you to use the first solution. I hope this helped.

    0 讨论(0)
提交回复
热议问题