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)
class A:
@MyDecorator("Blablabla")
def func1(self, arg1, arg2, arg3):
print (arg1,arg2,arg3)
You need to add the self argument to your function.
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.