python - Python:将装饰器存储在一个类中?
问题描述
我的装饰器工作得很好,现在存储在一个模块中。如果可能的话,我想将它存储在一个类中,而不是与相关功能一起放置。但是,我似乎无法让它工作,这是代码(没有不相关的部分):
class MqPubSubFwdController(object):
def __init__(self, address, port_pub, port_sub):
self.mq_path_list = []
self.mq_path_func = {}
def handle_mq(self, mq_path, cmd=None):
""" Decorator function.
Registers the MQ path
"""
def decorator(fn):
key = "my_key"
self.mq_path_list.append(prepostfix(mq_path).lower())
self.mq_path_func[key] = fn
def decorated(*args,**kwargs):
return fn(*args,**kwargs)
return decorated
return decorator
@messaging.handle_mq('/mode/set','PUT')
def mq_mode_set(path=None, cmd=None, args=None, data=None):
""" Set mode """
print "A MODE WAS SET"
return "A MODE WAS SET"
messaging = MqPubSubFwdController('localhost',1,2)
这将返回错误NameError: name 'messaging' is not defined on the @-decorator。有没有办法让它工作,以便我可以在位于类中时调用装饰器函数?我在 Python 2.7 上。
解决方案
就像 Aran-Fey 所说,这是关于位置的。需要先初始化该类,然后才能引用其中的装饰器函数。
这是正确的代码:
class MqPubSubFwdController(object):
def __init__(self, address, port_pub, port_sub):
self.mq_path_list = []
self.mq_path_func = {}
def handle_mq(self, mq_path, cmd=None):
""" Decorator function.
Registers the MQ path
"""
def decorator(fn):
key = "my_key"
self.mq_path_list.append(mq_path.lower())
self.mq_path_func[key] = fn
def decorated(*args,**kwargs):
return fn(*args,**kwargs)
return decorated
return decorator
messaging = MqPubSubFwdController('localhost',1,2)
@messaging.handle_mq('/mode/set','PUT')
def mq_mode_set(path=None, cmd=None, args=None, data=None):
""" Set mode """
print "A MODE WAS SET"
return "A MODE WAS SET"
推荐阅读
- python - 使用python添加excel公式时不需要的“@”字母
- excel - Powershell 无法向 Excel 单元格添加值
- angular - 用户定义的 HttpInterceptor 的 StaticInjectorError 异常
- python - 提示用户输入 sudo 密码以通过 tkinter GUI 和 python3 运行 shell 命令
- sql - 将每个月的日期时间段设置为日期之间
- python - 如何将列转为索引,将行转为列
- sql - 使用带有 IN 子句的 IS NULL 处理可选参数
- python - Pandas - 将组填充到最大值
- scheme - 在 Scheme 中编写尾递归过程
- python - 如何在 Cloud Run 上为 python 烧瓶应用启用云调试器