来自不同文件 Python 的全局变量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3400525/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 10:52:01  来源:igfitidea点击:

Global Variable from a different file Python

python

提问by Anon

So I have two different files somewhat like this:

所以我有两个不同的文件,有点像这样:

file1.py

文件1.py

from file2 import *
foo = "bar";
test = SomeClass();

file2.py

文件2.py

class SomeClass :
    def __init__ (self):
        global foo;
        print foo;

However I cannot seem to get file2 to recognize variables from file1 even though its imported into file1 already. It would be extremely helpful if this is possible in some way.

但是我似乎无法让 file2 识别来自 file1 的变量,即使它已经导入到 file1 中。如果这在某种程度上是可能的,那将是非常有帮助的。

采纳答案by Alex Martelli

Importing file2in file1.pymakes the global (i.e., module level) names bound in file2available to following code in file1-- the only such name is SomeClass. It does notdo the reverse: names defined in file1are not made available to code in file2when file1imports file2. This would be the case even if you imported the right way (import file2, as @nate correctly recommends) rather than in the horrible, horrible way you're doing it (if everybody under the Sun forgot the very existence of the construct from ... import *, life would be somuch better for everybody).

导入file2file1.py使得全球(即,模块级)的约束名字file2提供给下面的代码file1-唯一的此类名称是SomeClass。它并没有做反向:在定义的名称file1并不提供给代码file2的时候file1进口file2。即使您以正确的方式导入(import file2正如@nate 正确推荐的那样),而不是以您正在做的可怕的方式导入,情况也会如此(如果太阳底下的每个人都忘记了构造的存在from ... import *,生活将是所以更好的为大家)。

Apparently you want to make global names defined in file1available to code in file2andvice versa. This is known as a "cyclical dependency" and is a terribleidea (in Python, or anywhere else for that matter).

显然,你想在定义的全局名称file1提供给代码file2反之亦然。这被称为“循环依赖”并且是一个糟糕的想法(在 Python 或其他任何地方)。

So, rather than showing you the incredibly fragile, often unmaintainable hacks to achieve (some semblance of) a cyclical dependency in Python, I'd much rather discuss the many excellent way in which you can avoidsuch terrible structure.

因此,与其向您展示在 Python 中实现(某种表面上的)循环依赖的极其脆弱、通常无法维护的 hack,我宁愿讨论许多可以避免这种可怕结构的极好方法。

For example, you could put global names that need to be available to both modules in a thirdmodule (e.g. file3.py, to continue your naming streak;-) and import that third module into each of the other two (import file3in both file1and file2, and then use file3.fooetc, that is, qualifiednames, for the purpose of accessing or setting those global names from either or both of the other modules, notbarenames).

例如,您可以将需要对两个模块都可用的全局名称放在第三个模块中(例如file3.py,为了继续您的连续命名;-)并将该第三个模块导入其他两个模块中的每一个(import file3在两者file1和中file2,然后使用file3.foo等等,即限定名称,用于从其他模块中的一个或两个(而不是裸名)访问或设置这些全局名称)。

Of course, more and more specific help could be offered if you clarified (by editing your Q) exactly whyyou think you need a cyclical dependency (just one easy prediction: no matter what makes you think you need a cyclical dependency, you're wrong;-).

当然,如果您明确(通过编辑 Q)您认为需要循环依赖的确切原因(只是一个简单的预测:无论是什么让您认为需要循环依赖,您是错误的;-)。

回答by nate c

from file2 import *is making copies. You want to do this:

from file2 import *正在制作副本。你想这样做:

import file2
print file2.foo
print file2.SomeClass()

回答by msw

globalis a bit of a misnomer in Python, module_namespacewould be more descriptive.

global在 Python 中有点用词不当,module_namespace会更具描述性。

The fully qualified name of foois file1.fooand the global statement is best shunned as there are usually better ways to accomplish what you want to do. (I can't tell what you want to do from your toy example.)

最好避免使用fooisfile1.foo和 global 语句的完全限定名称,因为通常有更好的方法来完成您想做的事情。(我无法从您的玩具示例中看出您想做什么。)

回答by David Z

When you write

当你写

from file2 import *

it actually copiesthe names defined in file2into the namespace of file1. So if you reassign those names in file1, by writing

它实际上将 中定义的名称复制file2file1. 因此,如果您在 中重新分配这些名称file1,请写入

foo = "bar"

for example, it will only make that change in file1, not file2. Note that if you were to change an attributeof foo, say by doing

例如,它只会在 中进行更改file1,而不会在 中进行file2。请注意,如果你要改变一个属性foo,说做

foo.blah = "bar"

then that change would be reflected in file2, because you are modifying the existing object referred to by the name foo, not replacing it with a new object.

那么该更改将反映在 中file2,因为您正在修改 name 引用的现有对象foo,而不是用新对象替换它。

You can get the effect you want by doing this in file1.py:

您可以通过以下方式获得您想要的效果file1.py

import file2
file2.foo = "bar"
test = SomeClass()

(note that you should delete from foo import *) although I would suggest thinking carefully about whether you really need to do this. It's not very common that changing one module's variables from within another module is really justified.

(请注意,您应该删除from foo import *),尽管我建议您仔细考虑您是否真的需要这样做。从另一个模块中更改一个模块的变量确实是合理的,这并不常见。

回答by Helen

All given answers are wrong. It is impossible to globalise a variable inside a function in a separate file.

所有给出的答案都是错误的。不可能在单独的文件中将函数内的变量全球化。

回答by john ktejik

Just put your globals in the file you are importing.

只需将您的全局变量放在您要导入的文件中。

回答by Wahyu Bram

After searching, I got this clue: https://instructobit.com/tutorial/108/How-to-share-global-variables-between-files-in-Python

搜索后,我得到了这个线索:https: //instructobit.com/tutorial/108/How-to-share-global-variables-between-files-in-Python

the key is: turn on the function to call the variabel that set to global if a function activated.

关键是:如果一个函数被激活,打开函数调用设置为全局的变量。

then import the variabel again from that file.

然后从该文件再次导入变量。

i give you the hard example so you can understood:

我给你举了一个很难的例子,所以你可以理解:

file chromy.py

文件chromy.py

from selenium import webdriver
from selenium.webdriver.chrome.options import Options

def opennormal():
    global driver
    options = Options()
    driver = webdriver.Chrome(chrome_options=options)

def gotourl(str):
    url = str
    driver.get(url)

file tester.py

文件 tester.py

from chromy import * #this command call all function in chromy.py, but the 'driver' variable in opennormal function is not exists yet. run: dir() to check what you call.

opennormal() #this command activate the driver variable to global, but remember, at the first import you not import it

#then do this, this is the key to solve:
from chromy import driver #run dir() to check what you call and compare with the first dir() result.

#because you already re-import the global that you need, you can use it now

url = 'https://www.google.com'
gotourl(url)

That's the way you call the global variable that you set in a function. cheers don't forget to give credit

这就是调用在函数中设置的全局变量的方式。欢呼不要忘记给予信任