我的装饰工作得很好,现在存放在一个模块中。如果可能的话,我希望将其存储在类中,而不是将其存放在相关功能中。但是,我似乎无法让它工作,这是代码(没有相关的部分):
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'未在@ -decorator上定义。有没有办法让它工作,以便我可以在课堂上调用装饰器功能?我是Python 2.7。
答案 0 :(得分:0)
就像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"