Python: How do I pass a string by reference?

前端 未结 7 1075
清歌不尽
清歌不尽 2020-12-05 18:21

From this link: How do I pass a variable by reference?, we know, Python will copy a string (an immutable type variable) when it is passed to a function as a parameter, but I

7条回答
  •  天命终不由人
    2020-12-05 18:38

    Python does pass a string by reference. Notice that two strings with the same content are considered identical:

    a = 'hello'
    b = 'hello'
    a is b        # True
    

    Since when b is assigned by a value, and the value already exists in memory, it uses the same reference of the string. Notice another fact, that if the string was dynamically created, meaning being created with string operations (i.e concatenation), the new variable will reference a new instance of the same string:

    c = 'hello'
    d = 'he'
    d += 'llo'
    c is d        # False
    

    That being said, creating a new string will allocate a new string in memory and returning a reference for the new string, but using a currently created string will reuse the same string instance. Therefore, passing a string as a function parameter will pass it by reference, or in other words, will pass the address in memory of the string.

    And now to the point you were looking for- if you change the string inside the function, the string outside of the function will remain the same, and that stems from string immutability. Changing a string means allocating a new string in memory.

    a = 'a'
    b = a    # b will hold a reference to string a
    a += 'a'
    a is b   # False
    

    Bottom line:

    You cannot really change a string. The same as for maybe every other programming language (but don't quote me). When you pass the string as an argument, you pass a reference. When you change it's value, you change the variable to point to another place in memory. But when you change a variable's reference, other variables that points to the same address will naturally keep the old value (reference) they held. Wish the explanation was clear enough

提交回复
热议问题