2015-09-12 55 views
0

我有一個restful變量,我想在python中設置一個全局變量。設置一個函數內的全局python變量

此代碼有效。它允許腳本的其餘部分閱讀the_api 全球the_api

auth = tweepy.OAuthHandler(consumer_key, consumer_secret) 
auth.set_access_token(access_token, access_token_secret) 
the_api = tweepy.API(auth) 
print(the_api) 

此代碼設置the_api,但在其他功能the_api是不確定......爲什麼我不能VSET the_api從Python中的函數中。

def initTweepy(): 
    auth = tweepy.OAuthHandler(consumer_key, consumer_secret) 
    auth.set_access_token(access_token, access_token_secret) 
    the_api = tweepy.API(auth) 
    print(the_api) 
+1

您可以隨時讀出全局範圍的,但你必須先與變量的任何轉讓'全球[my_var]'如果你想更改爲當前範圍的有效之外。 – Alexander

回答

1

您需要使用global關鍵字否則Python將創建一個新的局部變量陰影全局變量。

def initTweepy(): 
    auth = tweepy.OAuthHandler(consumer_key, consumer_secret) 
    auth.set_access_token(access_token, access_token_secret) 
    global the_api 
    the_api = tweepy.API(auth) 
    print(the_api) 
相關問題