简体   繁体   English

用于类方法和函数的装饰器

[英]Decorator for both class methods and functions

I have a decorator 我有一个装饰师

def deco(func):
    def inner(params):
        #< DO STUFF WITH func >
    return inner

And a base class 一个基类

class GenericClass:
    def __init__(self,value):
        self.value = value
    def method(self,params):
        print 'NOT IMPLEMENTED YET'
    def other_method(self):
        print 'GOOD TO GO'

I would like to be able to decorate the "method" method on classes which are child of GenericClass, for exemple to check input/output or handle exceptions (the method "method" will be overrided) 我希望能够在GenericClass的子类上修饰“方法”方法,例如检查输入/输出或处理异常(方法“方法”将被覆盖)

what I want to do is something like... 我想做的是......

class ChildClass(GenericClass):
    @deco
    def method(self,params):
        #< NEW METHOD >

I am not an expert python developper and all the doc at that level is quite confusing (ie metaclasses, subtleties in decorators, __call__ method etc etc) and I didn't found the solution on SO. 我不是一个专家python开发人员,并且该级别的所有文档都非常令人困惑(即元类,装饰器中的细微之处, __call__方法等等),我没有在SO上找到解决方案。

Got it. 得到它了。 You are basically asking how to write a decorator which can be applied to both functions and methods. 您基本上是在询问如何编写可应用于函数和方法的装饰器。 It's possible: 这是可能的:

def deco(func):
    def inner(*args):
        print('DECORATED: args={}'.format(args))
        func(*args)
    return inner

class Class:
    @deco
    def method(self, param): print('PARAM is {}'.format(param))

@deco
def func(a, b, c): print('{} {} {}'.format(a, b, c))

Class().method('X')

func(1, 2, 3)

OUTPUT: OUTPUT:

DECORATED: args=(<__main__.Class instance at 0x7f740c6297a0>, 'X')
PARAM is X
DECORATED: args=(1, 2, 3)
1 2 3

PS PS

One year later I found one useful post (which was asked 8 years ago) here: Using the same decorator (with arguments) with functions and methods . 一年后,我在这里发现了一个有用的帖子(8年前被问过): 使用与函数和方法相同的装饰器(带参数) The approach described there will be useful if you are care of actual parameters of the decorated function. 如果你关心装饰函数的实际参数,那么在那里描述的方法将是有用的。

I figured it out. 我想到了。 The trick is that module-level functions (except for closures, I guess, which you probably don't want to decorate anyway) have a simple name while methods at least have two parts in their qualified name. 诀窍是模块级函数(除了闭包,我猜,你可能不想装饰它)有一个简单的名称,而方法至少有两个部分在他们的限定名称。 Forget about inspect.ismethod - for some reason it just won't work in this case, although it should be the obvious choice, possibly a bug. 忘记inspect.ismethod - 由于某种原因它在这种情况下不起作用,虽然它应该是明显的选择,可能是一个bug。

def can(*fargs):
    def wrapper(func):
        if len(func.__qualname__.split('.')) > 1:
            def calling(self, *args, **kwargs):
                self, thing = args[0], args[1]
                do_stuff(thing)
                func(*args, **kwargs)
        else:
            def calling(*args, **kwargs):
                thing = args[0]
                do_stuff(thing)
                func(*args, **kwargs)
        return calling
    return wrapper

class C:
    @can(2, 3)
    def test(self, x):
        print(7, ismethod(self.test), x)

@can()
def test(x):
    print(8, ismethod(test), x)

c = C()
c.test(12)

test(8)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM