装饰方法时访问绑定方法或自身

时间:2018-10-02 06:31:26

标签: python python-decorators python-descriptors

我有一个用例,我想用一种额外的方法来装饰方法,例如下面的代码:

def decorator(func):
    def enhanced(*args, **kwargs):
        func(*args, **kwargs)

    func.enhanced = enhanced
    return func

@decorator
def function():
    pass

class X:
    @decorator
    def function(self):
        pass

x = X()

function()
function.enhanced()
x.function()
# x.function.enhanced()
x.function.enhanced(x)

前三个呼叫按预期工作,但x.function.enhanced()无效;我必须写x.function.enhanced(x)才能使其正常工作。我知道这是因为传递给装饰器的func不是绑定方法,而是函数,因此需要显式传递self

但是我该如何解决?根据我对描述符的了解,它们仅在查找类时才有意义,并且由于func不是类,因此func.enhanced的查找方式不是我可以拦截的。

在这里我可以做些什么吗?

2 个答案:

答案 0 :(得分:4)

您可以返回一个descriptor,该对象返回一个本身可调用的对象,并且该对象具有一个enhanced属性映射到您的enhanced包装函数:

from functools import partial
def decorator(func):
    class EnhancedProperty:
        # this allows function.enhanced() to work
        def enhanced(self, *args, **kwargs):
            print('enhanced', end=' ') # this output is for the demo below only
            return func(*args, **kwargs)
        # this allows function() to work
        def __call__(self, *args, **kwargs):
            return func(*args, **kwargs)
        def __get__(self, obj, objtype):
            class Enhanced:
                # this allows x.function() to work
                __call__ = partial(func, obj)
                # this allows x.function.enhanced() to work
                enhanced = partial(self.enhanced, obj)
            return Enhanced()
    return EnhancedProperty()

这样:

@decorator
def function():
    print('function')

class X:
    @decorator
    def function(self):
        print('method of %s' % self.__class__.__name__)

x = X()

function()
function.enhanced()
x.function()
x.function.enhanced()

将输出:

function
enhanced function
method of X
enhanced method of X

答案 1 :(得分:3)

仅以我在@blhsing发布的答案的评论中的意思为例:

class EnhancedProperty:
    def __init__(self, func):
        self.func = func
    def enhanced(self, *args, **kwargs):
        return self.func(*args, **kwargs)
    def __call__(self, *args, **kwargs):
        return self.func(*args, **kwargs)
    def __get__(self, obj, typ):
        return Enhanced(self.func, obj, typ)

class Enhanced:
    def __init__(self, func, obj, typ):
        self.func = func
        self.obj = obj
        self.typ = typ
    def __call__(self, *args, **kwargs):
        return self.func.__get__(self.obj, self.typ)(*args, **kwargs)
    def enhanced(self, *args, **kwargs):
        return self.func(self.obj, *args, **kwargs)

def decorator(f):
    return EnhancedProperty(f)

在REPL中:

In [2]: foo(8, -8)
Out[2]: 1040

In [3]: foo.enhanced(8, -8)
Out[3]: 1040

In [4]: Bar().baz('foo')
Out[4]: ('foo', 'foo')

In [5]: Bar().baz.enhanced('foo')
Out[5]: ('foo', 'foo')