为什么 'api' 没有定义? (初学者)

Why 'api' is not defined? (beginner)

我想我将 'api' 定义为 twitter.api,不知道为什么会出现此错误 代码:

 import twitter


def auth():                      
    api = twitter.Api(consumer_key='CsqkkrnhBZQMhGLpnkqGqOUOV',
    consumer_secret='jzbWgRLZqIyJQjfh572LgbtuifBtXw6jwm1V94oqcQCzJd7VAE',
    access_token_key='1300635453247361031-EWTTGf1B6T2GUqWmFwzLfvgni3PoVH',
    access_token_secret='U2GZsWT0TvL5U24BG9X4NDAb84t1BB059qdoyJgGqhWN4')
                                
auth()
api.PostUpdate('Hello World')

 

错误:

Traceback (most recent call last):
  File "C:/Users/Xtrike/AppData/Local/Programs/Python/Python37/twitter python.py", line 11, in <module>
    api.PostUpdate('Hello World')
NameError: name 'api' is not defined

对于您发布的内容,您需要启动 api 变量。它只是获取所有内容并执行 PostUpdate,但首先您需要实例化它。

您可能需要了解 Python 中的 local and global scopes。简而言之,您创建了一个在函数外部不可见的局部变量 api

关于解决提供的错误,根据需要的结果有不同的方法:

  1. 使用保留字global使变量在全局范围可见:
def auth():
    global api # This does the trick publishing variable in global scope
    api = twitter.Api(consumer_key='<>',
        consumer_secret='<>',
        access_token_key='<>',
        access_token_secret='<>')
                                
auth()
api.PostUpdate('Hello World') # api variable actually published at global scope

但是我不建议使用没有适当意识的全局变量

  1. 提供的代码很小,因此无需包装到其他函数中
api = twitter.Api(consumer_key='<>',
        consumer_secret='<>',
        access_token_key='<>',
        access_token_secret='<>')
                                
api.PostUpdate('Hello World')
  1. 从函数返回对象 - 我推荐这种方法最合适和可靠
def auth():                      
    api = twitter.Api(consumer_key='<>',
        consumer_secret='<>',
        access_token_key='<>',
        access_token_secret='<>')
    return api
                                
api = auth()
api.PostUpdate('Hello World')

最后但重要的一句话:避免在 public 帖子中发布秘密 - 这些不是解决方案所必需的,但可能会暴露给破坏者。