python-3.x NameError:未定义全局名称“on_connect”

vshtjzan  于 2023-08-08  发布在  Python
关注(0)|答案(2)|浏览(97)
class HasadCoreManager:

    # The callback for when the client receives a connect response from the server.
    def on_connect(self, client, userdata, flags, rc):
        print("Connected with result code "+str(rc))
        client.subscribe(constants.MQTT_PATH_SUBSCRIBE)
        client.message_callback_add("hasadNode/water", on_message())
        client.message_callback_add("hasadNode/air", on_message())

字符串
当我在startingLooping函数中调用函数on_connect时,该函数是同一级别上同一类中的函数,如下所示:

def startLooping(self):
    print("Core Just started...")
    client = mqtt.Client()
    print("MQTT Client initialized")
    client.on_connect = on_connect
    client.on_message = on_message
    client.connect(constants.MQTT_SERVER, 1883, 60)
    client.loop_start()


我得到错误:NameError:未定义全局名称“on_connect”
怎么解决这个问题?

jw5wzhpr

jw5wzhpr1#

startLooping中,您编写

client.on_connect = on_connect

字符串
它在全局命名空间中查找名称on_connect。您希望使用HasadCoreManager的on_connect方法,因此应该

client.on_connect = self.on_connect


我可以想象,对于on_message的使用,您也会得到类似的错误

qlfbtfca

qlfbtfca2#

on_connect函数不需要是类的一部分。但是如果你想让它这样,那么它应该是一个静态方法。然后又道:

class HasadCoreManager:
    # The callback for when the client receives a connect response from the server.
    @staticmethod
    def on_connect(client, userdata, flags, rc):
        print("Connected with result code "+str(rc))
        client.subscribe(constants.MQTT_PATH_SUBSCRIBE)
        client.message_callback_add("hasadNode/water", on_message())
        client.message_callback_add("hasadNode/air", on_message())

字符串
注意方法签名是如何改变的。然后又道:

def startLooping(self):
    print("Core Just started...")
    client = mqtt.Client()
    print("MQTT Client initialized")
    client.on_connect = HasadCoreManager.on_connect
    #you will probably want something similar here
    client.on_message = on_message
    client.connect(constants.MQTT_SERVER, 1883, 60)
    client.loop_start()

相关问题