2013-07-30 208 views
0

我正在寻找装饰一个“可调用”类(其中一个具有定义的__call__方法),以便我可以在调用__init__之前启动后台服务,并在调用本身之前传递参数以包含该服务已启动。如何用类装饰器来装饰“可调用”类?

因此,举例来说:

@init_service # starts service on port 5432 
class Foo(object): 
    def __init__(self, port=9876): 
    # init here. 'port' should now be `5432` instead of the original `9876` 

    def __call__(self): 
    # calls the background service here, using port `5432` 

func = Foo(port=9876) 
... 
result = func() 

init_service将与端口号的一类属性,以便于以后的服务可以关机。

+0

这有什么好做的类被调用。 –

回答

2

您正在尝试修补__init__方法;有一个__call__方法的事实在这里也没什么不妥。

您通常会使用常规(函数)装饰器来装饰__init__方法;如果你使用类装饰,然后使用一个子类装饰类:

def init_service(cls): 
    class InitService(cls): 
     def __init__(self, port='ignored'): 
      super(InitService).__init__(5432) 

    return InitService 
+0

有没有什么办法可以在'init_service'函数之外定义这个类(它因为服务init方法而相当大),然后重新定义它在'init_service'函数中继承哪个对象? –

+0

@unpluggd:您需要一个定义继承的动态类。这可以是一个包装类,它只是执行'class WrapperInitService(RealInitServiceClass,cls)',其中'WrapperInitService'在装饰器之外。这有一些注意事项(主要是为了覆盖任何你需要使用'super()'做的事情),但它应该是正常工作。 –