类中的装饰器
问题描述:
我想创建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
想想复杂的,并不复杂。
答
你错了如何定义类方法。如果您想使用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风格就够了。 –
是的,'AppLogic.log_decorator'是一个未绑定的方法。你为什么把它放在课堂*中?这只是一个函数,并不使用“AppLogic”状态。 –
它实际上可以登录到AppLogic特定的输出流,我需要创建其他应用程序逻辑,如通知或捕获异常。我会更新我的例子。 –
然后,无论是将它变成一个'classmethod'(并接受一个'cls'参数,所以现在你有一个上下文)或一个'staticmethod'(在这一点上,我仍然会问为什么它是在你的课上)。 –