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

我想我将“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


动漫人物
浏览 88回答 2
2回答

Smart猫小萌

您可能需要了解Python 中的本地和全局作用域。简而言之,您创建了一个api在函数外部不可见的局部变量。在解决所提供的错误时,根据所需的结果有不同的方法:使用保留字global使变量在全局范围内可见:def auth():&nbsp; &nbsp; global api # This does the trick publishing variable in global scope&nbsp; &nbsp; api = twitter.Api(consumer_key='<>',&nbsp; &nbsp; &nbsp; &nbsp; consumer_secret='<>',&nbsp; &nbsp; &nbsp; &nbsp; access_token_key='<>',&nbsp; &nbsp; &nbsp; &nbsp; access_token_secret='<>')&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp;auth()api.PostUpdate('Hello World') # api variable actually published at global scope但是我不建议在没有适当简洁的情况下使用全局变量提供的代码很小,因此无需包装到额外的函数中api = twitter.Api(consumer_key='<>',&nbsp; &nbsp; &nbsp; &nbsp; consumer_secret='<>',&nbsp; &nbsp; &nbsp; &nbsp; access_token_key='<>',&nbsp; &nbsp; &nbsp; &nbsp; access_token_secret='<>')&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp;api.PostUpdate('Hello World')从函数返回对象 - 我推荐这种方法,因为它是最合适和可靠的def auth():&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; api = twitter.Api(consumer_key='<>',&nbsp; &nbsp; &nbsp; &nbsp; consumer_secret='<>',&nbsp; &nbsp; &nbsp; &nbsp; access_token_key='<>',&nbsp; &nbsp; &nbsp; &nbsp; access_token_secret='<>')&nbsp; &nbsp; return api&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp;api = auth()api.PostUpdate('Hello World')最后但很重要的一句话:避免在公共帖子中发布秘密 - 这些不是解决方案所必需的,但可能会暴露给破坏者。

慕容森

对于您发布的内容,您需要启动api变量。它只是获取所有内容并执行操作PostUpdate,但首先您需要实例化它。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python