未绑定本地错误

2024-09-29 19:28:35 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要帮助找出为什么会出现以下错误:

Traceback (most recent call last):
  File "prawtest3.py", line 25, in <module>
    commentMatcher()
  File "prawtest3.py", line 13, in commentMatcher
    commentCollection.append(comment)
UnboundLocalError: local variable 'commentCollection' referenced before assignment

这是我的密码。作为背景信息,我正在尝试创建一个reddit bot,它比较一个人的评论,然后在他们监视的人提交新评论时pms一个用户。如果您也看到了功能上的问题,请随意分享您的意见。我只需要先诊断代码,排除语法错误,然后再担心语义错误。你知道吗

import praw
import time 

r = praw.Reddit('PRAW related-question monitor by u/testpurposes v 1.0.')
r.login()
user = r.get_redditor('krumpqueen')
commentCollection = []
commentComparison = []

def commentMatcher():
    comments = user.get_comments(limit = 4)
    for comment in comments:
        commentCollection.append(comment)
    time.sleep(60)
    comments = user.get_comments(limit = 4)
    for comment in comments:
        commentComparision.append(comment)
    if commentCollection[1] != commentComparision[1]:
        r.send_message('krumpqueen', 'just made a new comment', 'go check now')
        commentCollection = list(commentComparision)
    else:
    r.send_message('krumpqueen', 'did not made a new comment', 'sorry')

while(True):
    commentMatcher()

Tags: inpyget错误linecommentcommentsfile
2条回答

你在commentCollection = list(commentComparision)里面做commentMatcher。因为您已经完成了这些操作,Python得出结论,您有一个本地名称commentCollection。你知道吗

您的代码失败的原因与

def foo():
    bar.append(3)
    bar = []

就会失败。你知道吗

要使commentCollection = list(commentComparision)成为a)重新绑定全局名称commentCollection,并且b)使其看起来根本不是本地名称,请在commentMatcher的定义中添加global commentCollection作为第一行。你知道吗

在严肃的代码中,您不希望像这样作为全局变量来管理您的状态,而是希望创建一个对象。你知道吗

使用commentCollection使python(错误地1)假定commentCollection是本地的(因为您稍后有一个赋值给它,并且没有global语句)。当您尝试附加到本地(尚未创建)时,python抛出UnboundLocalError。你知道吗

1当然,并不是python做出了错误的假设,这就是语言的工作原理。

相关问题 更多 >

    热门问题