python Realizes the Method of Modifying Variable Values in Functions
- 2021-07-18 08:34:17
- OfStack
Unlike other languages, python does not allow programmers to choose between passing values or references when passing parameters. Python parameter passing is definitely the way of "passing object reference".
In fact, this method is equivalent to a combination of value transmission and reference transmission. If the function receives a reference to a mutable object, such as a dictionary or list,
You can modify the original value of the object-equivalent to passing the object by "passing a reference". If the function receives a reference to an immutable object, such as a number, character, or tuple,
You can't modify the original object directly-it's equivalent to passing the object by "passing value".
python1-like internal assignment variables, are passed a reference variable, and C language passed the address of the concept is similar. You can use id () to query the memory address
The following str_ is a modifiable object, so it can be modified in the add function:
#!/usr/bin/env python
#coding=utf-8
def add(s):
s += 'b'
print "In add function :", s
if __name__ == "__main__":
str_ = list("aaa")
add(str_)
print "In main function:", str_
The output is:
In add function : ['a', 'a', 'a', 'b']
In main function: ['a', 'a', 'a', 'b']
The following str_ is an unmodifiable object and therefore cannot be modified in the add function:
#!/usr/bin/env python
#coding=utf-8
def add(s):
s += 'b'
print "In add function :", s
if __name__ == "__main__":
str_ = "aaa"
add(str_)
print "In main function:", str_
In add function : aaab
In main function: aaa
On the Replication of python
If a=b, the addresses of a and b are the same; If you just want to copy, you have to use a=b [:].
! ! ! Pay attention to this point, which can cause major mistakes. . .