简体   繁体   中英

Python How to Pass string to function by reference

def foo(arg1,arg2,arg3)
   arg3="new_value"
   return arg1+arg2
arg3=""
foo(1,2,arg3)

And I still get "" in arg3 after calling foo(). I want to get arg3=="new_value". How do I do that?

Python always receives parameters by value, so assigning a new value to a parameter variable inside the body of a function won't affect the caller.

If the value is mutable , then mutating it inside the body of the function will affect the caller, but strings are immutable (there's no method you can call on a string that will change its contents, only return a new string).

In general, the way to approach the situation you describe is to simply return multiple values:

def foo(arg1,arg2,arg3)
   arg3="new_value"
   return arg1+arg2, arg3
arg3=""
_, arg3 = foo(1, 2, arg3)

If you need an immutable argument to be mutable, though, an easy workaround (that doesn't involve using global ) is to wrap it in a mutable container, like a list:

def foo(arg1,arg2,arg3)
   arg3[0]="new_value"
   return arg1+arg2
arg3=[""]
foo(1,2,arg3)
# arg3[0] is now "new_value"

To manipulate an outside-function variable, you either have to return it, or use it as a global variable:

return

def foo(arg1, arg2, arg3):

    arg3 = "new_value"
    return arg1 + arg2, arg3

arg3 = ""
first_return, arg3 = foo(1, 2, arg3)

global

def foo(arg1, arg2):
    
    global arg3
    arg3 = "new_value"
    return arg1 + arg2

arg3 = ""
first_return = foo(1, 2)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM