简体   繁体   中英

How to pass variable reference to a method?

I have this method:

def add(st):
    st += "123"

how can I make the variable 'st' reference the variable that I passed from an outer scope when doing this:

s = "321"
add(s)
print(s)

the output should be:

321123

but is:

321

Python doesn't have variables so much as it has references, tied to names. Names can be reassigned, but that will never modify the original value the name used to point to.

If you're really set on persistently changing an object with the method, you can wrap whatever value you want in an object, and modify the property of that object:

class Wrapper:
    def __init__(self, obj):
        self.obj = obj

def add(st):
    st.obj += "123"

s = Wrapper("321")
add(s)
print(s.obj)

Otherwise, as other answers point out, the standard way to perform an operation that 'changes' an otherwise immutable object is to (1) create a new object that reflects the change, (2) return it, and (3) assign it over the original, outside the function:

def add(st):
    return st + "123"

s = "321"
s = add(s)
print(s)

You are missing a few lines of code. Here, this should work:

def add(st):
    st += "123"
    return st

s = "321"
s = add(s)
print(s)

You need a return statement that would update the value as:

def add(st):
    st += "123"
    return st

s = "321"
s = add(s)
print(s)

You can even make use of Global variable (but it is not generally recommended) as:

def add(s):
    global s
    s += "123"
    

global s
s = "321"
add(s)
print(s)

You can use return :

def add(st):
    st += "123"
    return st

st = add(st)
print(st)

or you can use global , in that case your code will work and you do not need to pass st as an argument

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