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

问题描述 投票:0回答:1

我在函数中定义了一个全局变量。但是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中导入mod

a.py:
g_handle =None # type: mods.handle_class

但这不是work.can't找不到mod所以我想知道如何让PyCharm将g_handle引用为mods.handle_class。谢谢。

python pycharm
1个回答
0
投票

我不确定这是否是你提问的方式的一个元素,但看起来你在这里遇到了多个问题。第一个是导入引用问题(或者可能使用导入,其中类更有效)。

请参阅,如果您只按照您所描述和提供的方式运行代码,那么您将永远无法获得正确的答案,因为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
© www.soinside.com 2019 - 2024. All rights reserved.