Python 装饰器是 class 中的一个方法,它在不同的模块中

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

我想使用装饰器,它是 class 中的一个函数,它位于不同的 python 模块中。

全局创建 class 的实例并使用像“@global_obj.my_decor”这样的装饰器会起作用。

但我怎么感觉它看起来不干净。还有其他方法吗?

如果您只是想避免全局对象(我可能会想要),您总是可以避免使用语法糖并手动创建、对象和装饰您的函数:

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

对我来说,这表明您一开始就没有 class 可能会更好。但没有更多细节,我只能猜测。