Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
tengwang0318 opened this issue Mar 3, 2022 · 0 comments

Comments

@tengwang0318
Copy link

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant