在函数中设置全局变量

时间:2014-04-04 04:02:53

标签: python global-variables

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

为什么以下全局变量始终等于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

2 个答案:

答案 0 :(得分:3)

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

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

答案 1 :(得分:2)

只需使用global关键字:

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