Decorate class-method with class-decorator

≡放荡痞女 提交于 2019-12-24 00:29:12

问题


I'm trying to decorate class method using class-decorator. For example

class MyDecorator(object):
    def __init__(self,param1):
        self.param1 = param1
        # do some action with param1

    def __call__(self,func):
        def wrapped(*args,**kwargs):
             print "in wrapper:"
             func(*args,**kwargs)

        return wrapped

and my some class:

class A:
    @MyDecorator("Blablabla")
    def func1(arg1,arg2,arg3):
         print (arg1,arg2,arg3)

but when I do the next action:

a = A()
a.func(1,2,3)

I get the following error:

TypeError: func1() takes exactly 3 arguments (4 given)

回答1:


class A:
    @MyDecorator("Blablabla")
    def func1(self, arg1, arg2, arg3):
        print (arg1,arg2,arg3)

You need to add the self argument to your function.




回答2:


If you prefer to write your func1 method without a first self argument, you need to drop this argument in the decorator:

def __call__(self, func):
    def wrapped(obj, *args, **kwargs):
         # obj is just ignored
         print "in wrapper:"
         func(*args, **kwargs)

This is quite the same as using @staticmethod: when calling a.func1, a is passed as first argument, but this argument is removed by the decorator.



来源:https://stackoverflow.com/questions/20787474/decorate-class-method-with-class-decorator

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!