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
想想複雜的,並不複雜。
是的,'AppLogic.log_decorator'是一個未綁定的方法。你爲什麼把它放在課堂*中?這只是一個函數,並不使用「AppLogic」狀態。 –
它實際上可以登錄到AppLogic特定的輸出流,我需要創建其他應用程序邏輯,如通知或捕獲異常。我會更新我的例子。 –
然後,無論是將它變成一個'classmethod'(並接受一個'cls'參數,所以現在你有一個上下文)或一個'staticmethod'(在這一點上,我仍然會問爲什麼它是在你的課上)。 –