简体   繁体   English

如何在模块中声明全局变量

[英]How to declare a global variable in a module

In the main program I have 在主程序中

import medallia_utils
from collections import defaultdict
Opers   = defaultdict(int)

Later on in this program, I will be calling a function in medallia_utils called word_checker. 在此程序的后面,我将在Medellia_utils中调用一个名为word_checker的函数。

I want to manipulate the dictionary variable Opers in a function word_checker defined inside medallia_utils so I want to declare it as Global. 我想在badgelia_utils内部定义的word_checker函数中操作字典变量Opers,因此我想将其声明为Global。

When I do this inside of medallia_utils: 当我在badgelia_utils内部执行此操作时:

def word_checker(name, comment):
    import re 
    from collections import defaultdict
    global Opers

The system says 系统说

NameError: global name 'Opers' is not defined

I also tried to define this variable globally in medallia_utils outside of the function word_checker by doing 我还尝试通过在word_checker函数外部的badgelia_utils中全局定义此变量

global Opers

or 要么

global __Opers__

but nothing working so far. 但到目前为止没有任何效果。 I get the same error. 我犯了同样的错误。

What is the syntax fix to get this to work? 使它起作用的语法修补程序是什么?

There is no "syntax fix" that can make this work. 没有可以使这项工作的“语法修复”。 If you want to use a variable defined in another module, you need to import it. 如果要使用另一个模块中定义的变量,则需要导入它。

you need to make the variable hold something after you declare it as global eg. 在将其声明为全局变量之后,需要使该变量保留某些内容。

global name 
name = 'bob'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM