在函数中设置全局变量



我有一个问题,我在函数中设置了一些全局变量。但是当我去函数外部(在脚本的主要部分)访问这些全局变量时,这些全局变量从未设置过?

为什么以下全局变量总是等于0而不是1?如何在函数中设置全局变量?

currentUserClientID             = 0
currentUserMaxLicences          = 0
currentUserActivatedLicences    = 0
def setGlobals():
    currentUserClientID             = 1
    currentUserMaxLicences          = 1
    currentUserActivatedLicences    = 1
    print "Set Globals"
    print currentUserClientID
    print currentUserMaxLicences
    print currentUserActivatedLicences
setGlobals()
print "Global Values"
print currentUserClientID
print currentUserMaxLicences
print currentUserActivatedLicences

输出:

Set Globals
1
1
1
Global Values
0
0
0

您必须将变量声明为全局变量。将 global 关键字放在函数内每个变量声明之前。

def setGlobals():
    global currentUserClientID
    global currentUserMaxLicences
    global currentUserActivatedLicences
    currentUserClientID = 1
    currentUserMaxLicenses = 1
    currentUserActivatedLicenses = 1
    print "Set Globals"
    print currentUserClientID
    print currentUserMaxLicences
    print currentUserActivatedLicences

只需使用 global 关键字:

def setGlobals():
    global currentUserClientID, currentUserMaxLicences, currentUserActivatedLicences
    currentUserClientID             = 1
    currentUserMaxLicences          = 1
    currentUserActivatedLicences    = 1
    print "Set Globals"
    print currentUserClientID, currentUserMaxLicences, currentUserActivatedLicences

相关内容

  • 没有找到相关文章

最新更新