python made easy: variable spaces in different files

15941271:

In Python programming, understanding how to manage variables in different files or modules is crucial to properly structure your program. This is a question about scope and namespaces.

namespace and scope

First, we need to understand what a namespace is. In Python, a namespace is a mapping from names (variable names, function names, etc.) to objects. The important thing to note is that there is no relationship between names in different namespaces. Thus, two different modules can both define a variable my_varwithout conflicts, since each module has its own namespace.

For example, consider two Python files:

In file1.py:

my_var = "Hello from file1"

In file2.py:

my_var = "Hello from file2"

In file1.py and file2.py my_varare two different variables. They exist in different namespaces and do not interfere with each other.

Import variables between modules

Although each module has its own namespace, Python allows you to access variables in one module in another module using the import statement.

In file1.py:

my_var = "Hello from file1"

In file2.py:

from file1 import my_var
print(my_var)  # 这将输出:Hello from file1

Here, my_var in file2.py is the same as my_var in file1.py because it was imported. However, if my_var is subsequently redefined in file2.py, this change will not affect the original my_var in file1.py.

Guess you like

Origin blog.csdn.net/robot_learner/article/details/131875449