Skip to main content
 首页 » 编程设计

python之如何在 Python 中自动将方法调用分派(dispatch)给多个处理程序

2025年02月15日7傻小

这是我的情况:

我有这样一个类:

class Handler: 
    def __init__(self, name): 
        self.name = name 
 
    def gogo(self, input): 
        print("My name is %s and I got %s" % (self.name, input)) 

我想要实现的是这样的:

dispatcher = Dispatcher(Handler("who"), Handler("what")) 
dispatcher.gogo("food") 
 
>> "My name is who and I got food" 
>> "My name is what and I got food" 

我的第一个尝试是创建一个 Dispatcher 类,该类在其 __init__ 方法中创建自己的方法。在这种情况下,Dispatcher 的每个方法都只会在不同的处理程序上触发相同的方法。缺点是如果在调度程序初始化后向处理程序添加任何新方法,它将无法工作。

所以我的第二次尝试是有一个 __getattr__ 方法,每次调用它时都会生成一个调用处理程序方法的新方法,所以基本上是这样的:

def __getattr__(self, item): 
    methods = [] 
    for destination in self._destinations: 
        if hasattr(destination, item): 
            destination_method = getattr(destination, item) 
 
            # if the argument is not callable, we are not interested, we cannot do anything with it 
            # Maybe we should even raise an error here? 
            if callable(destination_method): 
                methods.append(destination_method) 
 
    # If none of the destinations had a method for this name, we cannot do anything and should raise 
    if len(methods) == 0: 
        raise NotImplementedError("No method found for property %s" % item) 
 
    # Create a wrapper around the methods that we detected that will just pass the arguments 
    def new_method(*args, **kwargs): 
        for method in methods: 
            method(*args, **kwargs) 
 
    return new_method 

这个的缺点是每次都会生成一个新的方法,总的来说不是特别好。此外,它给人的感觉不是那么好,并且可能容易出错(例如,调度程序非常不透明,当您获得它时,您无法确定哪些方法可用或不可用)。

我想实现的方法数量是已知的,所以理论上我可以为所有处理程序创建一个基类,其中包含它们可能实现的每个方法。

我正在寻找一种尽可能优雅的解决方案,它不会在 dispatcher.gogo("food") 中涉及大量开销,因为它应该是一个非常简单的系统。

请您参考如下方法:

为什么不直接将调度程序方法从本地范围移动到实例级别?

class Dispatcher(): 
 
    def __dispatch(self, *args , **kwargs): 
        for method in self.__methods: 
            method(*args, **kwargs) 
 
    def __getattr__(self, item): 
        self.__methods = [] 
        … 
                if callable(destination_method): 
                    self.__methods.append(destination_method) 
        … 
        return self.__dispatch