[英]Modifying a variable in a module imported using from … import *
Consider the following code: 请考虑以下代码:
#main.py
From toolsmodule import *
database = "foo"
#toolsmodule
database = "mydatabase"
As it seems, this creates one variable in each module with different content. 看起来,这会在每个模块中创建一个具有不同内容的变量。 How can I modify the variable inside toolsmodule from main?
如何从main修改toolsmodule中的变量? The following does not work:
以下不起作用:
toolsmodule.database = "foo"
Sounds like yet another of the multitude of good reasons not to use from toolsmodule import *
. 听起来像是不使用
from toolsmodule import *
的众多好理由中的另一个。
If you just do import toolsmodule
, then you can do toolsmodule.database = 'foo'
, and everything is wonderful. 如果您只是
import toolsmodule
,那么您可以执行toolsmodule.database = 'foo'
,一切都很棒。
Pythons variable names are just labels on variables. Pythons变量名只是变量上的标签。 When you
import *
all those labels are local and when you then set the database, you just replace the local variable, not the one in toolsmodule. import *
所有这些标签都是本地的,当您设置数据库时,只需替换局部变量,而不是工具模块中的变量。 Hence, do this: 因此,这样做:
toolsmodule.py: toolsmodule.py:
database = "original"
def printdatabase():
print "Database is", database
And then run: 然后运行:
import toolsmodule
toolsmodule.database = "newdatabase"
toolsmodule.printdatabase()
The output is 输出是
Database is newdatabase
Note that if you then from ANOTHER module ALSO did an import *
the change is not reflected. 请注意,如果您从另一个模块ALSO执行了
import *
,则不会反映更改。
In short: NEVER use from x import *
. 简而言之:永远不要使用
from x import *
。 I don't know why all newbies persist in doing this despite all documentation I know of says that it's a bad idea. 我不知道为什么所有的新手都坚持这样做,尽管我所知道的所有文件都说这是个坏主意。
Why don't you do it like that: 你为什么不那样做:
import toolsmodule
toolsmodule.database = "foo"
from toolsmodule import * #bad idea, but let's say you have to..
print database #outputs foo
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.