首页 > 解决方案 > 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 上。

标签: pythonclasspython-decorators

解决方案


就像 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"

推荐阅读