[英]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. 我想使用装饰器,该装饰器是不同python模块中的类中的函数。
Creating an instance of the class globally and using the decorator like '@global_obj.my_decor' would work. 全局创建该类的实例,并使用装饰器(如'@ global_obj.my_decor')即可。
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.
但没有更多细节,我只能猜测。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.