Passing an integer by reference in Python

后端 未结 11 1695
天命终不由人
天命终不由人 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 12:55

    Maybe it's not pythonic way, but you can do this

    import ctypes
    
    def incr(a):
        a += 1
    
    x = ctypes.c_int(1) # create c-var
    incr(ctypes.ctypes.byref(x)) # passing by ref
    
    0 讨论(0)
  • 2020-11-22 13:01
    class PassByReference:
        def Change(self, var):
            self.a = var
            print(self.a)
    s=PassByReference()
    s.Change(5)     
    
    0 讨论(0)
  • 2020-11-22 13:02

    The correct answer, is to use a class and put the value inside the class, this lets you pass by reference exactly as you desire.

    class Thing:
      def __init__(self,a):
        self.a = a
    def dosomething(ref)
      ref.a += 1
    
    t = Thing(3)
    dosomething(t)
    print("T is now",t.a)
    
    
    0 讨论(0)
  • 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__.

    0 讨论(0)
  • 2020-11-22 13:08

    Most cases where you would need to pass by reference are where you need to return more than one value back to the caller. A "best practice" is to use multiple return values, which is much easier to do in Python than in languages like Java.

    Here's a simple example:

    def RectToPolar(x, y):
        r = (x ** 2 + y ** 2) ** 0.5
        theta = math.atan2(y, x)
        return r, theta # return 2 things at once
    
    r, theta = RectToPolar(3, 4) # assign 2 things at once
    
    0 讨论(0)
提交回复
热议问题