Recently I was reading something about decorator in Learning Python. By following an example of descriptor-as-decorator, I tried to write a different version of it.
class tracer3(object):
def __init__(self, func):
print func # what func should it be: bound, unbound, or function?
self.calls = 0
self.func = func
def __call__(self, *args, **kwargs):
self.calls += 1
print ('call %s to %s' % (self.calls, self.func.__name__))
return self.func(self.wrapped, *args, **kwargs)
def __get__(self, instance, owner):
self.wrapped = instance
return self
class Person:
@tracer3
def spam(self, say):
print 'Hello %s' % say
p = Person()
p.spam('world')
It yields
<function spam at 0x10b0260c8> call 1 to spam Hello world
Two questions about it:
- Is the decorator a correct one? From the result, it seems fine. But I'm just not sure about magic methods I used here.
- Notice the
print func
in__init__
. Whyfunc
here is just afunction
but neither abound
nor anunbound
one? And whyself.func(self.wrapped, *args, **kwargs)
can work by manually passing aself
as first argument? (Is the method just a that simple combination of a function and a instance as 1st argument?)