Mystery of Intramodule Variables in Python

Asked 2 years ago, Updated 2 years ago, 254 views

I'm afraid you'll scold me not to access the variables in the module, but is there any way to set a to 100 on main.py?

#main.py
from sub import*
foo()
print(a)#0 T-T)/
#sub.py
a = 0
def foo():
    global a
    a = 100

Also, the strange thing is that if you do the following, 100 will be displayed.

#main.py
from sub import*
baa()#100 is displayed 
#sub.py
a = 0
def foo():
    global a
    a = 100
defbaa():
    print(a)

T^T)/Thank you for your cooperation

python python3

2022-09-30 22:03

1 Answers

Answers to this article and Python documents will be helpful.The import and where the global variables are defined in this article itself are different from the current question.
Three patterns of action are described in the response.
Visibility of global variables in imported modules

Globals in Python are global to a module, not across all modules.

Python's Globals is global for (individual) modules, not all modules (for example, in C (language), many people are confused because global is the same for all implementation files unless explicitly static).

In other words, a that you can access by sub.py by import and a that you can access from sub.py are different things.

The same is true of Python documents:

How do I share global variables between modules?

A legitimate way to share information between modules in a program is to create a special module (often called config or cfg).Simply import the configuration module into all modules in the application.

Both articles are then instructed to access the variable with the module name ..


2022-09-30 22:03

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.