There are several modules as follows:
A.py
Function: Define a global variable, for use by other modules
name = "张三"
lists = [1, 2, 3, 4, 5]
B.py
features: variable print A.py in
from A import name,lists
def test():
print("B:",name)
print("B:",lists)
main.py
from A import name,lists
from B import test
if __name__ == '__main__':
print("修改前-main:",name)
name = "李四"
print("修改后-main:", name)
print("main:",lists)
lists.append(100)
# B模块中test的功能是打印A模块的name、lists
test()
"""
修改前-main: 张三
修改后-main: 李四
main: [1, 2, 3, 4, 5]
B: 张三
B: [1, 2, 3, 4, 5, 100]
"""
After the run we found:
- A module name is modified, but printed in the module B or the original value.
- A module lists adding new elements displayed properly.
the reason:
- Using from A import name is a name created in the current block variable that points to a value A module name variable points, i.e. Zhang, modify the value of the name is actually a reference to modify the name, the string is immutable type , name = "John Doe", was created in memory of John Doe string, and then redirected name John Doe, so before Joe Smith has not changed.
- And it is a list of lists, is a variable type, so add a new element in the list is feasible, but lists can not be reassigned, and its reference will change when the re-assignment.
Solution:
- The definitions of global variables used A.py import import.
Like this:
B.py
import A
def test():
print("B:",A.name)
print("B:",A.lists)
main.py
import A
from B import test
if __name__ == '__main__':
print("修改前-main:",A.name)
A.name = "李四"
print("修改后-main:", A.name)
print("main:",A.lists)
A.lists.append(100)
# B模块中test的功能是打印A模块的name、lists
test()
"""
修改前-main: 张三
修改后-main: 李四
main: [1, 2, 3, 4, 5]
B: 李四
B: [1, 2, 3, 4, 5, 100]
"""