dabeaz / python-cookbook

Code samples from the "Python Cookbook, 3rd Edition", published by O'Reilly & Associates, May, 2013.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

define an class to a decorator, how to understand this code, which is wraps(func)(self) without assignment

tengwang0318 opened this issue · comments

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"?