2015-09-12 52 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) 
相关问题