Skip to main content
 首页 » 编程设计

python之需要在 python 类中路由实例调用

2025年05月04日18arxive

问题是在选择响应者之前需要考虑参数。到目前为止,这是我的尝试。

from responders import A, B, C 
 
class RandomResponder(object) 
    def init(self, *args, *kwargs): 
        self.args = args 
        self.kwargs = kwargs 
 
    def __getattr__(self, name): 
        # pick a responder based on the args the function was called with 
        # I don't know how to do this part 
        # for sake of argument lets the args a function was called with lead me to pick responder A 
        r = A 
        responder = r(*self.args, **self.kwargs) 
        return responder.__getattr__(name) 

期望的效果是:

r = RandomResponder() 
r.doSomething(1) 
#returns A.doSomething() 
r.doSomething(2) 
#returns B.doSomething() 
r.doSomething(3) 
#return C.doSomething() 
r.doSomethingElse(1) 
#returns A.doSomethingElse() 
r.doSomethingElse(2) 
#returns B.doSomethingElse() 
r.doSomethingElse(3) 
#returns C.doSomethingElse() 

我不会提前知道响应器 A、B 和 C 包含的所有功能。

请您参考如下方法:

当你这样做的时候

r.doSomething(1) 

按顺序发生的事情是:

  • r.__getattr__ 被调用,并返回一个对象
  • 使用参数“1”调用此对象

在调用 __getattr__ 时,您无法知道您返回的对象将用什么参数来调用,或者即使它会完全被调用...

因此,要获得您想要的行为,__getattr__ 必须返回一个可调用对象,该对象根据它调用时使用的参数自行做出决定。例如

from responders import A, B, C 
 
class RandomResponder(object): 
    def __getattr__(self, name): 
        def func(*args, **kwds): 
            resp = { 1:A, 2:B, 3:C }[args[0]]    # Decide which responder to use (example) 
            return getattr(resp, name)()         # Call the function on the responder 
        return func