【问题标题】:Python Decorator cannot access called methodPython 装饰器无法访问被调用的方法
【发布时间】:2018-11-18 00:36:53
【问题描述】:

我正在尝试为将调用第二种方法的方法编写装饰器。当我运行代码时,我收到错误:
AttributeError: 'Backoff' object has no attribute 'formatter'

简化,代码为:

class Backoff:
    def __init__(self, f):
        self.f = f

    def __call__(self, *args, **kwargs):
        n = 1
        while n < 11:
            try:
                return self.f(self, *args, **kwargs)
            except FooError as e:
                <handle error>
                time.sleep((2 ** n) + (random.randint(0, 1000) / 1000))
                n = n + 1

class SomeClass:
    def __init__(self):
        pass
    @Backoff
    def first_method(self, foo, bar):
        return self.formatter(foo, bar)

    def formatter(self, x, y):
        return some_function_to_format(x, y)

如何以装饰器可以识别的方式将第二种方法传递给第一种方法?

任何帮助都会很棒!

【问题讨论】:

  • 您的 init 方法缺少 self 参数。格式化程序可能相同。
  • @jedwards 我收到一条错误消息,说在添加 self.我一开始也觉得没必要
  • @OlivierMelançon 原始代码在这两种方法中都有 self 参数,但是我快速转录到 StackOverflow 并错误地删除了它们。代码已编辑
  • 您能否提供可以运行的代码,except 语句不允许我复制粘贴您的代码并在没有 SyntaxError 的情况下运行它。请务必在询问之前阅读如何创建Minimal Verifiable Example,它可以帮助我们帮助您!
  • Here's an outstanding answer to a similar question,描述您的问题、问题以及解决方法。

标签: python python-3.x class python-decorators attributeerror


【解决方案1】:

您将一个方法传递给Backoff,将其分配为实例变量,然后调用它。在Backoff.__call__ 中调用它之前,它不会绑定到一个实例,然后它会绑定到一个没有formatter 属性的Backoff 实例。

这可能有一个简单的解决方案,具体取决于您的实例方法需要访问什么(即,如果它只需要引用一个类或静态方法,它可以直接调用完全限定名称)。但是,如果您需要实例方法来引用实例属性,我建议根本不要使用类装饰器。使用函数装饰器不会遇到这些问题,您可以创建一个闭包并返回具有相同调用签名的函数。

【讨论】:

  • 我不确定格式化程序 是否至少是一个类方法。
  • 非常感谢您提供了如此简单的解决方案!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-01-29
  • 2020-05-02
  • 2011-10-30
  • 1970-01-01
  • 1970-01-01
  • 2016-06-11
  • 2010-10-16
相关资源
最近更新 更多