2013-07-30 122 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()'做的事情),但它應該是正常工作。 –