2014-04-04 224 views
1

我有一個問題,我在一個函數內設置了一些全局變量。但是當我去訪問函數之外的這些全局變量時(在腳本的主要部分),那些全局變量從未被設置?在函數中設置全局變量

爲什麼以下全局變量總是等於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 
+0

可能重複(http://stackoverflow.com/questions/423379/使用全局變量在功能,其他不是那麼一個,創建它們) – Martey

回答

2

只需使用global關鍵字:比創建它們的另一個函數使用全局變量]的

def setGlobals(): 
    global currentUserClientID, currentUserMaxLicences, currentUserActivatedLicences 
    currentUserClientID    = 1 
    currentUserMaxLicences   = 1 
    currentUserActivatedLicences = 1 
    print "Set Globals" 
    print currentUserClientID, currentUserMaxLicences, currentUserActivatedLicences 
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 
+0

這會給你一個SyntaxError :) – aIKid

+0

謝謝,修正它:)忘記了語法。 – gregkow