【问题标题】:Python: Store decorator in a class?Python:将装饰器存储在一个类中?
【发布时间】:2018-11-17 20:38:58
【问题描述】:

我的装饰器工作得很好,现在存储在一个模块中。如果可能的话,我想将它存储在 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)

这会在@-decorator 上返回错误NameError: name 'messaging' is not defined。有没有办法让它工作,以便我可以在位于类中时调用装饰器函数?我在 Python 2.7 上。

【问题讨论】:

  • “它不起作用”是什么意思? 如何不起作用?它会抛出错误吗?它会让你的电脑着火吗?
  • “这不起作用。”。它是如何失败的?
  • 一旦我定义了一个占位符函数dispatcher_key,当我测试它时它运行得非常好。
  • 运行您的代码时出现的错误是“名称 DEFAULT_PORT_PUB 未定义”。然后“名称 dispatcher_key 未定义”。然后“未定义名称前缀”。这些是你要问的错误吗?可能不是。如果您希望我们帮助您,您需要发布minimal reproducible example
  • 重写为最小、完整和可验证。问题出在@messaging 装饰器行。当装饰器在课堂上时,我无法让它工作。

标签: python class python-decorators


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2011-09-29
    • 1970-01-01
    • 1970-01-01
    • 2017-11-16
    • 1970-01-01
    • 2015-02-22
    • 2011-04-28
    • 2012-04-11
    • 2011-09-03
    相关资源
    最近更新 更多