簡體   English   中英

在類方法和子類方法上使用python裝飾器

[英]Use python decorators on class methods and subclass methods

目標:可以裝飾類方法。 當修飾一個類方法時,它會存儲在字典中,以便其他類方法可以通過字符串名稱引用它。

動機:我想實現等效於ASP.Net的WebMethods。 我在google app引擎上構建此文件,但這並不影響我遇到的困難。

如果有效,它將如何:

class UsefulClass(WebmethodBaseClass):
    def someMethod(self, blah):
        print(blah)

    @webmethod
    def webby(self, blah):
        print(blah)

# the implementation of this class could be completely different, it does not matter
# the only important thing is having access to the web methods defined in sub classes
class WebmethodBaseClass():
    def post(self, methodName):
        webmethods[methodName]("kapow")

    ...    

a = UsefulClass()
a.post("someMethod") # should error
a.post("webby")  # prints "kapow"

可能還有其他方法可以解決此問題。 我很願意提出建議

這是不必要的。 只需使用getattr

class WebmethodBaseClass():
    def post(self, methodName):
        getattr(self, methodName)("kapow")

唯一的警告是,您必須確保只能使用打算用作網絡方法的方法。 IMO最簡單的解決方案是采用以下約定:非web方法以下划線開頭,並要求post方法拒絕為此類名稱提供服務。

如果您真的想使用裝飾器,請嘗試以下操作:

def webmethod(f):
    f.is_webmethod = True
    return f

並在調用該方法之前獲取post以檢查is_webmethod屬性是否存在。

如上所述,這似乎是滿足您的規格的最簡單方法:

webmethods = {}

def webmethod(f):
    webmethods[f.__name__] = f
    return f

並且,在WebmethodBaseClass

def post(self, methodName):
    webmethods[methodName](self, "kapow")

我懷疑您想要不同的東西(例如,不同子類的單獨名稱空間與單個全局webmethods字典...?),但是如果沒有更多信息,很難猜測您的需求與規范有何不同-因此也許您可以告訴我們這種簡單的方法如何無法實現您的某些需求,因此可以根據您的實際需求進行豐富。

class UsefulClass(WebmethodBaseClass):

    def someMethod(self, blah):
        print(blah)

    @webmethod
    def webby(self, blah):
        print(blah)

class WebmethodBaseClass():
    def post(self, methodName):
        method = getattr(self, methodName)
        if method.webmethod:
            method("kapow")

    ...

def webmethod(f):
    f.webmethod = True
    return f

a = UsefulClass()
a.post("someMethod") # should error
a.post("webby")  # prints "kapow"

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM