问题
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