如果我有一个以回调函数为参数的函数,如果回调函数带有一些参数集,我如何创建一个函数器对象来代替回调函数?
Context:
卡夫卡制作人接受回调函数.
producer.produce(
topic=topic,
key=key,
value=value,
callback=delivery_callback
)
callback_count = 0
def delivery_callback(error, message_payload):
if error:
print(f'{error}')
else:
global callback_count
callback_count += 1
# count the number of successfully
# delivered messages
此回调函数统计成功传递的消息数.
Problems with this design and proposed solution
这种设计的问题是显而易见的--使用全局变量.
我的第一个本能是设计某种仿函数对象,它可能会定义__call__
使其可调用.
class DeliveryCallbackCounter():
def __init__(self) -> None:
self.count_callback = 0
def __call__(self, error, message):
if error:
print(f'ERROR: Kafka: Message delivery failure: {error}')
else:
self.count_callback += 1
def __str__(self) -> str:
return f'DeliveryCallbackCounter: callback count: {self.count_callback}'
这可以通过以下方式使用,并且确实有效.
delivery_callback_counter = DeliveryCallbackCounter()
producer.produce(
topic=topic,
key=key,
value=value,
callback=delivery_callback_counter
)
但是,这个解决方案的工作方式与前面的选项不完全相同,因为类DeliveryCallbackCounter
不是静态的.以前,当使用函数而不是函子(类)作为回调函数时,修改数据count_callback
是具有静态生命周期 的全局变量.
有了函数器,我们就有了一些稍有不同的东西,并且可以创建类DeliveryCallbackCounter
的许多实例化.
Python类有一些类似于静态方法的东西,由@classmethod
decorator 表示.
有没有可能通过在Python中构建一个"静态类"来重现"函数选项"所提供的相同语义?我对Python不太熟悉,不知道该怎么做.