【问题标题】:What is equivalent of @error_wrap decorator in python? [duplicate]python中的@error_wrap装饰器等效于什么? [复制]
【发布时间】:2018-05-24 15:44:33
【问题描述】:

python中的一些函数上面的@error_wrap是什么?
比如下面的代码:

@error_wrap
def disconnect(self):
    """
    disconnect a client.
    """
    logger.info("disconnecting snap7 client")
    return self.library.Cli_Disconnect(self.pointer)

error_wrap 方法:

def error_wrap(func):
    """Parses a s7 error code returned the decorated function."""
    def f(*args, **kw):
        code = func(*args, **kw)
        check_error(code, context="client")
    return f

我知道几个 OOP 修饰的 python 函数,(即@staticmethod、@classmethod、@abstractmethod 等),但我找不到关于@error_wrap。
这些代码的等价物是什么?

【问题讨论】:

  • 嗯,它不是来自标准库。所以,你必须在你看到它被使用的代码库中搜索它。很可能来自这里:github.com/gijzelaerr/python-snap7/blob/master/snap7/…
  • 谢谢,我在内部库代码中找到它(作为一种方法),但它是如何工作的?
  • @BenyaminJafari 这是一个decorator
  • @AshwiniChaudhary ,好的,我找到了 error_wrap() 方法,但我不知道它在某些功能上作为装饰器是如何工作的
  • @BenyaminJafari 有很多关于 Python 装饰器的问题和文章。在其代码中是否有任何您不理解的具体内容?您还应该在问题正文中发布其代码。

标签: python oop python-decorators


【解决方案1】:

Python 装饰器也是函数,但函数的第一个参数是其他函数。下面的代码和你的一样

def error_wrap(f):
    # do something with received function f, then return it

def disconnect(self):
    # implementation of your function

disconnect= error_wrap(disconnect) # <- notice the function `disconnect` isn't called

现在您想知道error_wrap 函数的作用。好吧,我们不能回答这个问题,因为它只是另一个函数,所以你应该找到它并粘贴她的代码,然后我们会回答你的。

【讨论】:

  • error_wrap 是您在上面粘贴的函数。装饰器只是一个函数的名称,它将另一个函数作为其输入并执行某些操作然后返回该函数。由于这被标记为重复,您可以创建另一个问题,询问来自 error_wrap 的代码的作用。干杯
猜你喜欢
  • 2020-06-29
  • 2016-08-10
  • 1970-01-01
  • 2013-11-17
  • 1970-01-01
  • 2021-08-13
  • 1970-01-01
  • 2011-01-02
  • 2012-01-09
相关资源
最近更新 更多