如何在python中获取函数的返回值

2024-06-12 13:32:13 发布

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

import gnsq

class something():
    def __init__(self, pb=None, pk=None, address=None):
        self.pb = pb
        self.pk = pk
        self.address = address

    def connect(self):
        consumer = gnsq.Consumer(self.pb, 'ch', self.address)

        @consumer.on_message.connect
        def response_handler(consumer, msg):
           return msg.body

        consumer.start()

如何得到response_handler的返回值,这样,我就可以传递给父函数connect(),所以当我调用它时,它将从子函数返回message.body的值。你知道吗

我会这样想:

import gnsq

class something():
    def __init__(self, pb=None, pk=None, address=None):
        self.pb = pb
        self.pk = pk
        self.address = address

    def connect(self):
        consumer = gnsq.Consumer(self.pb, 'ch', self.address)

        @consumer.on_message.connect
        def response_handler(consumer, msg):
           return msg.body

        consumer.start()

       return response_handler

nsq = something('pb', 'pk', 'address')

# should print whatever message.body is
print nsq.connect() 

但它不起作用。注意:consumer.start()是阻塞的


Tags: selfnonemessageconsumeraddressresponsedefconnect
1条回答
网友
1楼 · 发布于 2024-06-12 13:32:13

你所问的在Consumer()真正的上下文中没有意义。你知道吗

connect()方法中,设置使用者,设置响应处理程序,并用consumer.start()启动使用者。从那时起,每当有消息要使用时,使用者都会用该消息调用处理程序。不只是一次,而是一次又一次。你知道吗

您的处理程序可能会被多次调用,除非使用者已关闭,否则您永远不知道何时会执行此操作—因此,您的connect()方法无法返回完整的结果。你知道吗

您可以做的是让connect方法返回对集合的引用,该集合将随时包含迄今为止收集的所有消息。它一开始是空的,但过了一段时间,可能包含所有接收到的消息。你知道吗

比如:

import gnsq

class Collector():
    def __init__(self, topic, address):
        self.topic = topic
        self.address = address
        self.messages = []

    def connect(self):
        self.messages = []
        consumer = gnsq.Consumer(self.pb, 'ch', self.address)

        @consumer.on_message.connect
        def response_handler(consumer, msg):
           self.messages.append(msg)

        consumer.start()
        return self.messages

我不认为这是你真正想要的使用方法,只有你提供更多的背景说明为什么以及如何使用这个输出,这才是真正有意义的。你知道吗

相关问题 更多 >