4

这只是一个想知道为什么这不起作用的问题。我想出了一个更好的方法,但我不知道为什么以前它不起作用。

global mydict
mydict = {}

这似乎工作正常,并使 mydict 字典全球化。我什至打印 mydict 并且它有效。但是,这样做:

global bool
bool = False

似乎不起作用。如果尝试在我的代码中打印 bool,我会得到:

UnboundLocalError: local variable 'bool' referenced before assignment

那么为什么它适用于字典而不是布尔值呢?

哦,另外,如果有人想知道我是如何找到更好的方法的,我初始化了一个类,并通过以下方式在类中使 bool 全局化: self.bool = False 哪个有效。我从这个问题中得到它:使所有变量全局化


编辑:根据要求,我将发布必要的代码:

import chatbot
global mydict
mydict = {}
global haveamessage
haveamessage = False

class MyBot(chatbot.ChatBot):
    def __init__(self, username, password, site):
        chatbot.ChatBot.__init__(self,username,password,site)

    def on_message(self, c, e):
        print mydict
        print haveamessage

if __name__ == '__main__':
    bot = MyBot("MyUsername", "MyPassword", "MySite")
    bot.start()

我会尝试解释这段代码。聊天机器人模块几乎是允许用户在 Wikia 上的 wiki 中创建机器人,Wikia 是一家允许创建任何人都可以编辑的 wiki 的公司。在 wiki 上有一个聊天扩展,用户可以在其中交谈。该脚本允许机器人加入聊天并执行命令。当有人在聊天中发布内容时,on_message() 会关闭。

所以这打印:

{}
Traceback (most recent call last):
  File "file.py", line 146, in <module>
    bot.start()
  File "/Library/Python/2.7/site-packages/chatbot.py", line 371, in start
    self.on_message(self.c, e)
  File "file.py", line 12, in on_message
    print haveamessage
UnboundLocalError: local variable 'haveamessage' referenced before assignment

我想澄清一下,这不会对你们所有人产生错误的原因是因为您不在 Wikia 聊天中。on_message() 函数仅在有人在聊天中发布内容时运行。例如,我可能有:

def on_message(self, c, e):
    if e.text == 'hello': # e.text is what a user posts in the chat. e = event
        c.send('Hello!') # c.send simply sends back a message in the chat. c = connection

因此,当有人在聊天 hello 中发帖时,Bot 会回复 Hello!

4

2 回答 2

6

您发布的代码不会产生您声称的错误。但是global,在函数之外使用关键字没有任何效果,因此它不会像您期望的那样工作也就不足为奇了。

我假设在您的真实代码中,您实际上是在尝试分配到haveamessageinside on_message。如果是这样,您需要global在该方法中声明。

基本上规则是:如果您尝试从函数中分配全局变量,则需要global在该函数中使用关键字。否则,您根本不需要global关键字。变量是否为布尔值没有区别。

于 2013-01-20T01:42:00.477 回答
0

我相信您想要做的是定义全局变量,然后在您的函数中引用它们,以便您可以在本地使用它们:

import chatbot
mydict = {}
haveamessage = False

class MyBot(chatbot.ChatBot):
    def __init__(self, username, password, site):
        chatbot.ChatBot.__init__(self,username,password,site)

    def on_message(self, c, e):
        global mydict
        global haveamessage
        print mydict
        print haveamessage
于 2013-01-20T01:41:35.703 回答