【问题标题】:Python3 bounding methods from decorators来自装饰器的 Python3 边界方法
【发布时间】:2013-01-16 22:09:40
【问题描述】:

在 Python 3 中没有绑定方法(在 Python 2 中已知),但我们总是创建函数。

在类中声明一个函数后,会创建自动 Python 描述符,当此函数将作为实例方法调用时,它将附加 self 作为第一个参数。

所以基本上,下面的代码:

def funcdecorator(func):
    def f(*args, **kwargs):
        print('funcdecorator:', args, kwargs)
    return f

class X:
    @funcdecorator
    def f(self):
        pass

X().f()

将输出:

funcdecorator: (<__main__.X object at ...>,) {}

(第一个参数作为self传递)

但使用以下代码:

def classdecorator(func):
    class C:
        def __call__(*args, **kwargs):
            print('classdecorator:', args, kwargs)
    return C()

class X:
    @classdecorator
    def f(self):
        pass

X().f()

我们得到:

classdecorator: (<__main__.C object at 0x1bbea10>,) {}

这是合乎逻辑的。

但是,是否有可能从装饰器返回一个类实例并模仿它是一个函数,所以当“调用”它时,第一个传递的参数将是X 的实例,而不是C 的实例?

【问题讨论】:

  • 将是 XX 的实例?
  • 当然,我在问题中解决了它。
  • “在 Python 3 中没有绑定方法” - Really?

标签: python methods python-3.x decorator bounding


【解决方案1】:

C 类必须是descriptor,即实现__get__。然后,X().f() 将首先调用描述符的 __get__,传递 X 实例和对 X 的引用。无论 __get__ 返回什么,都会看到 __call__ 被调用。

【讨论】:

    猜你喜欢
    • 2021-02-21
    • 2021-11-04
    • 2020-01-11
    • 2018-09-12
    • 2014-01-14
    • 2019-02-22
    • 1970-01-01
    • 2019-01-01
    • 1970-01-01
    相关资源
    最近更新 更多