[英]How can I use a decorator inside a class with the definition in the same module?
在BasePlugin
模塊內部,我定義了2個主要內容。 一個名為BasePlugin
的類,以及一個不屬於ValidateEvent
類的裝飾器。
當我編寫一個插件並運行時:
from BasePlugin import *
這可行,我可以在插件類中的方法上使用裝飾器。
但是,如果我嘗試在BasePlugin
類中裝飾一個方法,則它找不到裝飾器。
我嘗試了許多方法來引用裝飾器,甚至嘗試將其導入到它自己的模塊中,但是似乎沒有任何效果。 我寧願不為裝飾器創建另一個模塊。
是否可以在同一模塊中定義的類中引用裝飾器,而不是作為該類的一部分?
編輯:這是有問題的代碼的片段
#BasePlugin.py
class BasePlugin():
def __init__(self, event_manager):
pass
@ValidateEvent
def ProvideModeEventHandler(self, event):
self._mode = event.Message
def ValidateEvent(func):
"""
Decorator used to check if the event(s) fired should be
handled by the plugin.
"""
def new_func(plugin, event, *args, **kwargs):
if plugin.Name == event.Name or event.Name == '':
return func(plugin, event, *args, **kwargs)
return new_func
您遇到的問題與模塊中定義的順序有關。 當您將ValidateEvent
用作BasePlugin
類中方法的裝飾器時,它必須已在全局名稱空間中可用,因為裝飾器在定義方法時立即運行(不僅在調用方法時)。
在顯示的代碼片段中, ValidateEvent
是在類定義下方定義的,因此Python解釋器尚不知道。
要解決此問題,請將裝飾器的定義移到類定義上方:
def ValidateEvent(func):
...
class BasePlugin():
@ValidateEvent
def ProvideModeEventHandler(self, event):
...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.