Python: 在 class 中存储装饰器?

Python: Store decorator in a class?

我的装饰器工作得很好,现在存储在一个模块中。如果可能的话,我想将它存储在 class 中,而不是它将与相关功能放在一起的地方。但是,我似乎无法让它工作,这是代码(没有不相关的部分):

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)

这 returns 错误 NameError: name 'messaging' 未定义 在 @-decorator 上。有没有办法让它工作,以便我可以在位于 class 时调用装饰器函数?我在 Python 2.7.

正如Aran-Fey 所说,这是关于位置的。 class需要先初始化,才能引用里面的装饰函数

这是正确的代码:

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"