对象通过提供__call__(slef, [,*args [,**kwargs]])方法可以模拟函数的行为,如果一个对象x提供了该方法,就可以像函数一样使用它,也就是说x(arg1, arg2...) 等同于调用x.__call__(self, arg1, arg2) 。
class DistanceForm(object):
def __init__(self, origin):
self.origin = origin
print "origin :"+str(origin)
def __call__(self, x):
print "x :"+str(x)
p = DistanceForm(100)
p(2000)
输出
>>>
origin :100
x :2000
举例:
ReplyWaiter初始化时会调用declare_direct_consumer函数生成consumer,传给改函数的第二个参数self,等同于传的self.__call__函数,最终这个参数赋值给consumer对象的callback变量。
class ReplyWaiter(object): def __init__(self, reply_q, conn, allowed_remote_exmods): self.conn = conn self.allowed_remote_exmods = allowed_remote_exmods self.msg_id_cache = rpc_amqp._MsgIdCache() self.waiters = ReplyWaiters() self.conn.declare_direct_consumer(reply_q, self) self._thread_exit_event = threading.Event() self._thread = threading.Thread(target=self.poll) self._thread.daemon = True self._thread.start() def __call__(self, message): message.acknowledge() incoming_msg_id = message.pop('_msg_id', None) self.waiters.put(incoming_msg_id, message)
def declare_direct_consumer(self, topic, callback): """Create a 'direct' queue. In nova's use, this is generally a msg_id queue used for responses for call/multicall """ self.declare_consumer(DirectConsumer, topic, callback)
class ConsumerBase(object): """Consumer base class.""" def __init__(self, channel, callback, tag, **kwargs): """Declare a queue on an amqp channel. 'channel' is the amqp channel to use 'callback' is the callback to call when messages are received 'tag' is a unique ID for the consumer on the channel queue name, exchange name, and other kombu options are passed in here as a dictionary. """ self.callback = callback self.tag = six.text_type(tag) self.kwargs = kwargs self.queue = None self.reconnect(channel)