pycharm 不能在函数中引用全局变量



i定义了函数中的全局变量。但是pycharm不能引用此全局变量。这样的代码:

a.py:
g_Handle = None
def Init():
    import mods
    global g_handle
    g_handle = mods.handle_class()
b.py:
import a
a.g_handle 
# PyCharm will reference 'g_handle' as None,
# but I want reference 'g_handle' as mods.handle_class

我尝试为g_handle添加类型,但我不想直接在a.py

中导入mods
a.py:
g_handle =None # type: mods.handle_class

但这是不起作用的。因此,我想知道如何让Pycharm可以将g_handle引用为mods.handle_class。谢谢。

我不确定这是否是您提出问题的元素,但看起来您在这里遇到了多个问题。第一个是导入参考问题(或可能使用类更有效的导入)。

请参阅,如果您仅按照您描述和提供的代码运行代码,则永远不会得到您寻求的正确答案,因为A.Py中的INIT函数永远不会被调用。

您需要在像您的代码中一样使用之前的全局范围中以某种方式定义了预期的全局变量。

全局语句仅告诉解释器将所有州提供的变量的值链接。它不会自行定义最外面范围的变量。

因此,类似的东西(编辑:固定):

a.py:
g_handle = False
def Init():
    import mods
    global g_handle
    g_handle = mods.handle_class()
b.py:
import a
a.Init()
a.g_handle

...应该努力返回您要寻找的东西。

如果您可以使用类而不是从另一个模块导入,则也可以从麻烦中保存自己:

import mods
class a():
    g_handle = False
    global g_handle
    def __init__(self, handle_class):
        g_handle = handle_class()
if __name__ == "__main__":
    a(mods.handle_class).g_handle

最新更新