我有3个文件。一个用于定义变量,另外两个包含所需的模块。
变量.py
my_var = ""
Run Code Online (Sandbox Code Playgroud)
测试.py
import variable
def trial():
variable.my_var = "Hello"
Run Code Online (Sandbox Code Playgroud)
main.py(不工作)
from variable import *
from test import trial
if __name__ == "__main__":
trial()
print my_var
Run Code Online (Sandbox Code Playgroud)
当我跑步时main.py,它什么也没给出。然而,如果我main.py这样改变的话,
main.py(工作中)
import variable
from test import trial
if __name__ == "__main__":
trial()
print variable.my_var
Run Code Online (Sandbox Code Playgroud)
它给了我预期的输出,即Hello。
就我而言,它variable.py包含更多变量,我不想variable.<variable name>在访问它们时使用它们。在修改它们时,使用variable.<variable name>不是问题,因为我只会根据用户的输入修改一次,然后在其余时间多次跨多个文件访问它们。
main.py现在我的问题是,有没有办法在修改后提取所有变量test.py并在没有前缀的情况下使用它们variable.?
你想要达到的目标是不可能的。from MODULE import *将所有变量名称和值导入到您的命名空间中,但不导入变量本身。这些变量是在本地命名空间中分配的,因此更改它们的值不会反映到它们的来源上。但是,可变对象的更改会得到反映,因为您导入的值基本上是对实例的引用。
That is one of the many reasons why unqualified imports using the above construct are not recommended. Instead, you should question your program structure and the design decisions you took. Working with a huge amount of module-level variables can become cumbersome and very inconvenient in the long term.
Think about using a more structured approach to your application, for example by using classes.
Again I would like to point out and give credits to this thread which, in essence, addresses the same problem.
EDIT For the sake of completeness. It is possible, but this approach is not recommended. You would have to re-import the module every time you apply modifications to its non-referential variables:
from variable import * # optional
from test import trial
if __name__ == "__main__":
trial()
from variable import * # simply re-import the variables...
print my_var
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2061 次 |
| 最近记录: |