2017-05-31 99 views
1

我想創建2層應用程序,其中一個類中的應用程序邏輯和第二類中的業務。而我想要做到的,是這樣的:類中的裝飾器

# app_logic.py 
class AppLogic(object): 
    """docstring for AppLogic""" 
    def __init__(self, arg): 
     super(AppLogic, self).__init__() 
     self.output = open('log.txt', 'w') 

    def log_decorator(f): 
     def wrapper(self, *args, **kwargs): 
      self.output.write(f, ' was called') 
      return f(*args, **kwargs) 
     return wrapper 


# bus_logic.py 
from app_logic import AppLogic 

class BusinessLogic(AppLogic): 
    """docstring for BusinessLogic""" 
    def __init__(self, arg): 
     super(BusinessLogic, self).__init__() 

    @AppLogic.log_decorator 
    def function(self, arg0): 
     # complex magic 
     return 

但這裏是一個小問題,當我運行py.test TOX爲python2.7,它說,log_decorator綁定。我認爲這個示例架構可以簡化,但我不知道如何。

UPDATE

我已經結束了與此:

# utils.py 
plugin_manager_singleton = PManagerSingelton() 

def log(f): 
    def w(self, *args, **kwargs): 
     plugin_manager.call_log(f) 
     return f(*args, **kwargs) 
    return w 

# bus_logic.py 
from utils import log, plugin_manager_singleton 

class App(object): 
    """docstring for App""" 

    def __init__(self, arg): 
     super(App, self).__init__() 
     self.arg = arg 

    @log 
    def sensetive_method(self, arg): 
     special_log_plugin = plugin_manager_singleton.get('special_log') 
     # complex magic 
     return 

想想複雜的,並不複雜。

+0

是的,'AppLogic.log_decorator'是一個未綁定的方法。你爲什麼把它放在課堂*中?這只是一個函數,並不使用「AppLogic」狀態。 –

+0

它實際上可以登錄到AppLogic特定的輸出流,我需要創建其他應用程序邏輯,如通知或捕獲異常。我會更新我的例子。 –

+1

然後,無論是將它變成一個'classmethod'(並接受一個'cls'參數,所以現在你有一個上下文)或一個'staticmethod'(在這一點上,我仍然會問爲什麼它是在你的課上)。 –

回答

0

你錯了如何定義類方法。如果您想使用log_decorator作爲類方法,則不能使用self

class AppLogic(object): 

    log = 'log.txt' 

    @classmethod 
    def log_decorator(cls, f): 
     def wrapper(self, *args, **kwargs): 
      with open(cls.log, 'w') as fp: 
       fp.write(f, ' was called') 
      return f(*args, **kwargs) 
     return wrapper 
+0

謝謝,但是代碼風格太複雜了。我簡化了我的架構,現在很明顯。我不需要兩層,utils風格就夠了。 –