Source From Here
Question
I have the following code. I'm decorating the foo() method in bar, using the dec_check class as a decorator:
When executing this I was hoping to see:
But I'm getting "TypeError: foo() takes exactly 1 argument (0 given)" as .foo(), being an object method, takes self as an argument. I'm guessing problem is that the instance of bar doesn't actually exist when I'm executing the decorator code.
HowTo
You need to make the decorator into a descriptor -- either by ensuring its (meta)class has a __get__ method, or, way simpler, by using a decorator function instead of a decorator class (since functions are already descriptors). E.g.:
Execution output:
I have the following code. I'm decorating the foo() method in bar, using the dec_check class as a decorator:
- class dec_check(object):
- def __init__(self, f):
- self.func = f
- def __call__(self):
- print 'In dec_check.__init__()'
- self.func()
- class bar(object):
- @dec_check
- def foo(self):
- print 'In bar.foo()'
- b = bar()
- b.foo()
But I'm getting "TypeError: foo() takes exactly 1 argument (0 given)" as .foo(), being an object method, takes self as an argument. I'm guessing problem is that the instance of bar doesn't actually exist when I'm executing the decorator code.
HowTo
You need to make the decorator into a descriptor -- either by ensuring its (meta)class has a __get__ method, or, way simpler, by using a decorator function instead of a decorator class (since functions are already descriptors). E.g.:
- def dec_check(f):
- def deco(*args, **kargs):
- print(f'In deco: *args={args}; **kargs={kargs}')
- f(*args, **kargs)
- return deco
- class bar(object):
- def __init__(self, age):
- self.age = age
- @dec_check
- def foo(self, name):
- print(f'In bar.foo: Hello {name}, my age is {self.age}')
- b = bar(36)
- b.foo('John')
沒有留言:
張貼留言