我的装饰器工作得很好,现在存储在一个模块中。如果可能的话,我想把它存储在类中,而不是与相关函数一起存放的地方。然而,我似乎无法让它工作,这是代码(没有不相关的部分):
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上定义。有没有办法让它工作,这样我就可以在类中调用decorator函数?我使用的是python2.7。你知道吗
就像阿兰菲说的,是关于地点的。 在引用类中的decorator函数之前,需要初始化该类。你知道吗
这是正确的代码:
相关问题 更多 >
编程相关推荐