Passing an integer by reference in Python

后端 未结 11 1693
天命终不由人
天命终不由人 2020-11-22 12:29

How can I pass an integer by reference in Python?

I want to modify the value of a variable that I am passing to the function. I have read that everything in Python i

11条回答
  •  北海茫月
    2020-11-22 13:08

    It doesn't quite work that way in Python. Python passes references to objects. Inside your function you have an object -- You're free to mutate that object (if possible). However, integers are immutable. One workaround is to pass the integer in a container which can be mutated:

    def change(x):
        x[0] = 3
    
    x = [1]
    change(x)
    print x
    

    This is ugly/clumsy at best, but you're not going to do any better in Python. The reason is because in Python, assignment (=) takes whatever object is the result of the right hand side and binds it to whatever is on the left hand side *(or passes it to the appropriate function).

    Understanding this, we can see why there is no way to change the value of an immutable object inside a function -- you can't change any of its attributes because it's immutable, and you can't just assign the "variable" a new value because then you're actually creating a new object (which is distinct from the old one) and giving it the name that the old object had in the local namespace.

    Usually the workaround is to simply return the object that you want:

    def multiply_by_2(x):
        return 2*x
    
    x = 1
    x = multiply_by_2(x)
    

    *In the first example case above, 3 actually gets passed to x.__setitem__.

提交回复
热议问题