[英]Python decorator that is a method in a class which is in different module
我想使用裝飾器,該裝飾器是不同python模塊中的類中的函數。
全局創建該類的實例,並使用裝飾器(如'@ 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
對我來說,這表明如果沒有開始上課,您可能會更好。 但沒有更多細節,我只能猜測。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.