python-cookbook
python-cookbook copied to clipboard
define an class to a decorator, how to understand this code, which is wraps(func)(self) without assignment
Hi,
In chapter 9.9, I don't understand the below code, especially in __init__()
. It uses wraps(func)(self)
in __init__()
, but it doesn't assign wraps(func)(self)
to self
. Why self.__wrapped__
can get the original function in __call__()
?
import types
from functools import wraps
class Profiled:
def __init__(self, func):
wraps(func)(self)
self.ncalls = 0
def __call__(self, *args, **kwargs):
self.ncalls += 1
return self.__wrapped__(*args, **kwargs)
def __get__(self, instance, cls):
if instance is None:
return self
else:
return types.MethodType(self, instance)
@Profiled
def add(x, y):
return x + y
print(add(1, 2))
print(add(1, 3))
print(add.ncalls)
print(add)
I changed it to self = wraps(func)(self)
, found that it also can work? Who can explain that? I also couldn't understand self
in self = wraps(func)(self)
. What's "self"?