2 回答

TA貢獻1911條經驗 獲得超7個贊
您可能需要了解Python 中的本地和全局作用域。簡而言之,您創建了一個api在函數外部不可見的局部變量。
在解決所提供的錯誤時,根據所需的結果有不同的方法:
使用保留字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
但是我不建議在沒有適當簡潔的情況下使用全局變量
提供的代碼很小,因此無需包裝到額外的函數中
api = twitter.Api(consumer_key='<>',
consumer_secret='<>',
access_token_key='<>',
access_token_secret='<>')
api.PostUpdate('Hello World')
從函數返回對象 - 我推薦這種方法,因為它是最合適和可靠的
def auth():
api = twitter.Api(consumer_key='<>',
consumer_secret='<>',
access_token_key='<>',
access_token_secret='<>')
return api
api = auth()
api.PostUpdate('Hello World')
最后但很重要的一句話:避免在公共帖子中發布秘密 - 這些不是解決方案所必需的,但可能會暴露給破壞者。
添加回答
舉報