0

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

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 机器人来比较一个人的评论,然后在他们监控的人提交新评论时向用户发送消息。如果您也发现该功能存在问题,请随时分享您的意见。我只需要先诊断我的代码以消除语法错误,然后再担心语义错误。

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()
4

2 回答 2

1

你在commentCollection = list(commentComparision)里面做commentMatcher。因为你已经这样做了,Python 得出结论你有一个本地名称commentCollection

您的代码失败的原因与代码相同

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

会失败。

要获得commentCollection = list(commentComparision)a) 重新绑定全局名称commentCollection,并且 b) 根本不让它看起来像一个本地名称,请添加global commentCollectioncommentMatcher.

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

于 2014-02-04T03:31:39.597 回答
1

您对commentCollectionmake python 的使用(错误地1)假定它commentCollection是本地的(因为您稍后对其进行了分配并且没有global声明)。当您尝试附加到本地(尚未创建)时,python 会抛出 UnboundLocalError。

1当然,这不是 python 做出不正确的假设,这就是该语言的设计方式。

于 2014-02-04T03:06:52.197 回答