代码之家  ›  专栏  ›  技术社区  ›  Steven

将sqlContext作为全局变量[重复]

  •  1
  • Steven  · 技术社区  · 8 年前

    文件1.py

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

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

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

    0 回复  |  直到 16 年前
        1
  •  60
  •   robertspierre    9 年前

    file2 在里面 file1.py 使全局(即模块级)名称绑定到 文件2 file1 --唯一这样的名字是 SomeClass 执行相反的操作:在中定义的名称 文件1 无法在中进行编码 文件2 什么时候 文件1 . 即使你进口的方式正确,情况也是如此( import file2 ,正如@nate正确地建议的那样)而不是用可怕的、可怕的方式来做(如果太阳底下的每个人都忘记了这个构造的存在 from ... import * 所以 对每个人都好得多)。

    显然你想在 文件1 文件2 反之亦然。这被称为“周期依赖”,是一种 可怕的 idea(在Python或其他任何地方)。

    如此可怕的结构。

    例如,可以在 第三的 file3.py ,继续命名;-)并将第三个模块导入其他两个模块中( import file3 两者兼而有之 文件2 ,然后使用 file3.foo 有资格的 名称,用于从另一个模块或两个模块访问或设置这些全局名称, 光名)。

    当然,如果你能明确(通过编辑你的Q)你可以提供越来越具体的帮助 你认为你需要一个循环依赖(只是一个简单的预测:不管是什么让你认为你需要一个循环依赖,你错了;-)。

        2
  •  16
  •   David Z    16 年前

    from file2 import *
    

    事实上 中定义的名称 file2 的命名空间中 file1 . 所以如果你重新分配这些名字 文件1 ,通过书写

    foo = "bar"
    

    ,不是 文件2 属性 属于 foo

    foo.blah = "bar"
    

    然后这种变化就会反映在 文件2 ,因为您正在修改名称所引用的现有对象

    你可以通过这样做得到你想要的效果 file1.py :

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

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

        3
  •  13
  •   Nakilon earlonrails    13 年前

    from file2 import * 正在复印。你想这样做:

    import file2
    print file2.foo
    print file2.SomeClass()
    
        4
  •  5
  •   msw    16 年前

    global module_namespace 会更具描述性。

    的完全限定名 foo file1.foo 全球声明最好回避,因为通常有更好的方法来完成你想做的事情。(我无法从你的玩具例子中看出你想做什么。)

        5
  •  2
  •   Wahyu Bram    7 年前

    https://instructobit.com/tutorial/108/How-to-share-global-variables-between-files-in-Python

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

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

    我给你举个很难理解的例子:

    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)
    

    文件测试仪.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)
    

    别忘了表扬

        6
  •  -5
  •   Helen    9 年前

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

        7
  •  -5
  •   john k    8 年前

    只要把你的全局设置到你要导入的文件中。