使用类作为方法装饰器

时间:2017-03-08 11:53:57

标签: python class decorator python-decorators

虽然有plenty of resources about using classes as decorators,但我无法找到任何解决装饰方法的问题。这个问题的目标是解决这个问题。我会发布我自己的解决方案,但当然其他人也被邀请发布他们的解决方案。

为什么“标准”实施不起作用

标准装饰器类实现的问题是python不会创建装饰函数的绑定方法:

class Deco:
    def __init__(self, func):
        self.func= func

    def __call__(self, *args):
        self.func(*args)

class Class:
    @Deco
    def hello(self):
        print('hello world')

Class().hello() # throws TypeError: hello() missing 1 required positional argument: 'self'

方法装饰者需要克服这个障碍。

要求

参加上一个示例中的类,预计以下内容将起作用:

>>> i= Class()
>>> i.hello()
hello world
>>> i.hello
<__main__.Deco object at 0x7f4ae8b518d0>
>>> Class.hello is Class().hello
False
>>> Class().hello is Class().hello
False
>>> i.hello is i.hello
True

理想情况下,函数的__doc__以及签名和类似属性也会被保留。

1 个答案:

答案 0 :(得分:4)

通常当一个方法被访问为some_instance.some_method()时,python的descriptor protocol会启动并调用some_method.__get__(),它会返回一个绑定方法。但是,因为该方法已被Deco类的实例替换,所以不会发生 - 因为Deco不是描述符。为了使Deco按预期工作,它必须实现一个__get__方法,该方法返回自身的绑定副本。

实施

这是基本的“无所事事”装饰类:

import inspect
import functools
from copy import copy


class Deco(object):
    def __init__(self, func):
        self.__self__ = None # "__self__" is also used by bound methods

        self.__wrapped__ = func
        functools.update_wrapper(self, func)

    def __call__(self, *args, **kwargs):
        # if bound to an object, pass it as the first argument
        if self.__self__ is not None:
            args = (self.__self__,) + args

        #== change the following line to make the decorator do something ==
        return self.__wrapped__(*args, **kwargs)

    def __get__(self, instance, owner):
        if instance is None:
            return self

        # create a bound copy
        bound = copy(self)
        bound.__self__ = instance

        # update __doc__ and similar attributes
        functools.update_wrapper(bound, self.__wrapped__)

        # add the bound instance to the object's dict so that
        # __get__ won't be called a 2nd time
        setattr(instance, self.__wrapped__.__name__, bound)

        return bound

要让装饰器执行某些操作,请使用__call__方法添加代码。

这是一个参数:

class DecoWithArgs(object):
    #== change the constructor's parameters to fit your needs ==
    def __init__(self, *args):
        self.args = args

        self.__wrapped__ = None
        self.__self__ = None

    def __call__(self, *args, **kwargs):
        if self.__wrapped__ is None:
            return self.__wrap(*args, **kwargs)
        else:
            return self.__call_wrapped_function(*args, **kwargs)

    def __wrap(self, func):
        # update __doc__ and similar attributes
        functools.update_wrapper(self, func)

        return self

    def __call_wrapped_function(self, *args, **kwargs):
        # if bound to an object, pass it as the first argument
        if self.__self__ is not None:
            args = (self.__self__,) + args

        #== change the following line to make the decorator do something ==
        return self.__wrapped__(*args, **kwargs)

    def __get__(self, instance, owner):
        if instance is None:
            return self

        # create a bound copy of this object
        bound = copy(self)
        bound.__self__ = instance
        bound.__wrap(self.__wrapped__)

        # add the bound decorator to the object's dict so that
        # __get__ won't be called a 2nd time
        setattr(instance, self.__wrapped__.__name__, bound)
        return bound

这样的实现允许我们在方法和函数上使用装饰器,所以我认为它应该被视为良好的实践。

相关问题