Python decorator question
decorator 1:
def dec(f):
def wrap(obj, *args, **kwargs):
f(obj, *args,**kwargs)
return wrap
decorator 2:
class dec:
def __init__(self, f):
self.f = f
def __call__(self, o开发者_Go百科bj, *args, **kwargs):
self.f(obj, *args, **kwargs)
A sample class,
class Test:
@dec
def disp(self, *args, **kwargs):
print(*args,**kwargs)
The follwing code works with decorator 1 but not with decorator 2.
a = Test()
a.disp("Message")
I dont understand why decorator 2 is not working here. Can someone help me with this?
When you decorate with the dec
class, your disp
method is no more an instance method, but an instance of class dec
. So a.disp
is just a plain member of Test
, which happens to be callable because it has a __call__
method, and in the self passed as the first argument of its f
instance is "Message"
(it is by no way bound to the "test" instance).
with the decorator function:
a = Test()
print a.disp
# disp <bound method Test.wrap of <__main__.Test instance at 0xb739df0c>>
with the decorator class:
a = Test()
print a.disp
# disp <__main__.dec instance at 0xb739deec>
edit That should answer your question far better and clearer than I did:
http://irrepupavel.com/documents/python/instancemethod/
精彩评论