Class 来自其他 class 方法的装饰器

Class decorator for methods from other class

注意:
我在这里有一个相关的问题: How to access variables from a Class Decorator from within the method it's applied on?


我打算编写一个相当复杂的装饰器。因此,装饰器本身应该是一个 class 自己的。我知道这在 Python (Python 3.8):

中是可能的
import functools

class MyDecoratorClass:
    def __init__(self, func):
        functools.update_wrapper(self, func)
        self.func = func
    
    def __call__(self, *args, **kwargs):
        # do stuff before
        retval = self.func(*args, **kwargs)
        # do stuff after
        return retval

@MyDecoratorClass
def foo():
    print("foo")

现在,当我尝试将装饰器应用于 方法 而不仅仅是一个函数时,我的问题就开始了 - 特别是如果它是 来自另一个 [=91] 的方法=]。让我向您展示我的尝试:


1。试验一:身份丢失

下面的装饰器 MyDecoratorClass 没有(或不应)做任何事情。它只是样板代码,可以稍后使用。来自 class Foobar 的方法 foo() 打印调用它的对象:

import functools

class MyDecoratorClass:
    def __init__(self, method):
        functools.update_wrapper(self, method)
        self.method = method

    def __call__(self, *args, **kwargs):
        # do stuff before
        retval = self.method(self, *args, **kwargs)
        # do stuff after
        return retval

class Foobar:
    def __init__(self):
        # initialize stuff
        pass

    @MyDecoratorClass
    def foo(self):
        print(f"foo() called on object {self}")
        return

现在您在这里观察到 foo() 方法中的 self 被交换了。它不再是 Foobar() 实例,而是 MyDecoratorClass() 实例:

>>> foobar = Foobar()
>>> foobar.foo()
foo() called from object <__main__.MyDecoratorClass object at 0x000002DAE0B77A60>

换句话说,方法foo()失去了它原来的身份。这将我们带到下一个试验。


2。试验二:保持身份,但崩溃

我试图保留 foo() 方法的原始身份:

import functools

class MyDecoratorClass:
    def __init__(self, method):
        functools.update_wrapper(self, method)
        self.method = method

    def __call__(self, *args, **kwargs):
        # do stuff before
        retval = self.method(self.method.__self__, *args, **kwargs)
        # do stuff after
        return retval

class Foobar:
    def __init__(self):
        # initialize stuff
        pass

    @MyDecoratorClass
    def foo(self):
        print(f"foo() called on object {self}")
        return

现在让我们测试一下:

>>> foobar = Foobar()
>>> foobar.foo()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 7, in __call__
AttributeError: 'function' object has no attribute '__self__'

赞!


编辑
感谢@AlexHall 和@juanpa.arrivillaga 提供的解决方案。他们都工作。但是,它们之间有细微的差别。

我们先来看看这个:

def __get__(self, obj, objtype) -> object:
    temp = type(self)(self.method.__get__(obj, objtype))
    print(temp)
    return temp

我引入了一个临时变量,只是为了打印什么__get__() returns。每次访问方法 foo() 时,此 __get__() 函数 returns 一个新的 MyDecoratorClass() 实例:

>>> f = Foobar()
>>> func1 = f.foo
>>> func2 = f.foo
>>> print(func1 == func2)
>>> print(func1 is func2)
<__main__.MyDecoratorClass object at 0x000001B7E974D3A0>
<__main__.MyDecoratorClass object at 0x000001B7E96C5520>
False
False

第二种方法(来自@juanpa.arrivillaga)不同:

def __get__(self, obj, objtype) -> object:
    temp = types.MethodType(self, obj)
    print(temp)
    return temp

输出:

>>> f = Foobar()
>>> func1 = f.foo
>>> func2 = f.foo
>>> print(func1 == func2)
>>> print(func1 is func2)
<bound method Foobar.foo of <__main__.Foobar object at 0x000002824BBEF4C0>>
<bound method Foobar.foo of <__main__.Foobar object at 0x000002824BBEF4C0>>
True
False

有细微差别,但我不确定为什么。

函数是描述符,这就是允许它们 auto-bind 自我的原因。处理这个问题的最简单方法是使用函数实现装饰器,以便为您处理。否则您需要显式调用描述符。这是一种方法:

import functools


class MyDecoratorClass:
    def __init__(self, method):
        functools.update_wrapper(self, method)
        self.method = method

    def __get__(self, instance, owner):
        return type(self)(self.method.__get__(instance, owner))

    def __call__(self, *args, **kwargs):
        # do stuff before
        retval = self.method(*args, **kwargs)
        # do stuff after
        return retval


class Foobar:
    def __init__(self):
        # initialize stuff
        pass

    @MyDecoratorClass
    def foo(self, x, y):
        print(f"{[self, x, y]=}")


@MyDecoratorClass
def bar(spam):
    print(f"{[spam]=}")


Foobar().foo(1, 2)
bar(3)

这里的 __get__ 方法使用绑定方法创建了 MyDecoratorClass 的新实例(之前 self.method 只是一个函数,因为还没有实例存在)。另请注意 __call__ 仅调用 self.method(*args, **kwargs) - 如果 self.method 现在是绑定方法,则 FooBarself 已经隐含。

您可以实现描述符协议,Descriptor HOWTO 中提供了函数如何执行此操作的示例(但在纯 python 中),翻译成您的情况:

import functools
import types

class MyDecoratorClass:
    def __init__(self, func):
        functools.update_wrapper(self, func)
        self.func = func

    def __call__(self, *args, **kwargs):
        # do stuff before
        retval = self.func(*args, **kwargs)
        # do stuff after
        return retval

    def __get__(self, obj, objtype=None):
        if obj is None:
            return self
        return types.MethodType(self, obj)

注意,return types.MethodType(self, obj) 本质上等同于

return lambda *args, **kwargs : self.func(obj, *args, **kwargs)

Note from Kristof
Could it be that you meant this:

return types.MethodType(self, obj) is essentially equivalent to

return lambda *args, **kwargs : self(obj, *args, **kwargs)

Note that I replaced self.func(..) with self(..). I tried, and only this way I can ensure that the statements at # do stuff before and # do stuff after actually run.