Python:类中的存储装饰器?

Python:类中的存储装饰器?,python,class,python-decorators,Python,Class,Python Decorators,我的装饰师工作得很好,现在存储在一个模块中。如果可能的话,我希望将它存储在一个类中,而不是与相关函数一起存放。然而,我似乎无法让它工作,这是没有不相关部分的代码: class MqPubSubFwdController(object): def __init__(self, address, port_pub, port_sub): self.mq_path_list = [] self.mq_path_func = {} def handl

我的装饰师工作得很好,现在存储在一个模块中。如果可能的话,我希望将它存储在一个类中,而不是与相关函数一起存放。然而,我似乎无法让它工作,这是没有不相关部分的代码:

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:@-decorator上未定义名称“messaging”。有没有一种方法可以让它工作,这样我就可以在类中调用decorator函数?我使用的是Python 2.7。

正如Aran Fey所说,这是关于位置的。 在引用类中的decorator函数之前,需要初始化该类

这是正确的代码:

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"

你说它不起作用是什么意思?它怎么不起作用?它会抛出错误吗?这会让你的电脑着火吗?这不起作用。。它是如何失败的?一旦我定义了占位符函数dispatcher\u键,当我测试它时,它运行得非常好。当我运行代码时得到的错误是name DEFAULT\u PORT\u PUB未定义。则未定义名称调度程序密钥。那么名称prepostfix没有定义。这些是你要问的错误吗?可能不会。如果您希望我们帮助您,您需要发布一个。重写为最小、完整和可验证的。问题出在@messaging decorator行上。当装饰师在教室里时,我不能让它工作。