简体   繁体   中英

Python decorator that is a method in a class which is in different module

I want to use a decorator which is a function in a class that is in different python module.

Creating an instance of the class globally and using the decorator like '@global_obj.my_decor' would work.

But I somehow feel it doesn't look clean. Is there any other way to do it?

If you simply want to avoid a global object (I probably would want to), you can always just avoid the syntactic sugar and create and object and decorate your function by hand:

In [23]: class Foo:
    ...:     def deco(self, f):
    ...:         def wrapper(*args, **kwargs):
    ...:             print("hi")
    ...:             result = f(*args, **kwargs)
    ...:             print("I am decorated")
    ...:             return result
    ...:         return wrapper
    ...:

In [24]: def func(x, y):
    ...:     return 2*x + 3*y
    ...:
    ...:

In [25]: func = Foo().deco(func)

In [26]: func(3,2)
hi
I am decorated
Out[26]: 12

To me, this suggests that you might be better off without the class to begin with. But without more details, I can only guess.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM