在类方法和子类方法上使用python修饰符

2024-09-30 14:35:31 发布

您现在位置:Python中文网/ 问答频道 /正文

目标:使装饰类方法成为可能。当一个类方法被修饰时,它被存储在字典中,以便其他类方法可以通过字符串名引用它。在

动机:我想实现ASP.Net的WebMethods。我是在googleappengine的基础上构建的,但这并不影响我现在遇到的困难点。在

如果它有效的话会是什么样子:

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"

可能还有别的办法。我很乐意接受建议


Tags: the方法self目标defpostclassblah
3条回答

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

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

唯一需要注意的是,您必须确保只有打算用作webmethods的方法才能这样使用。IMO最简单的解决方案是采用一种约定,即非webmethods以下划线开头,并让post方法拒绝服务此类名称。在

如果您真的想使用装饰器,请尝试以下方法:

^{pr2}$

并在调用方法之前让post检查is_webmethod属性是否存在。在

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"

这似乎是满足您所述规格的最简单方法:

webmethods = {}

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

而且,在WebmethodBaseClass

^{pr2}$

我怀疑你想要不同的东西(例如,不同子类的单独名称空间与单个全局webmethods字典…?),但如果没有更多的信息,很难猜测你的欲望与你的规格有什么不同,所以也许你可以告诉我们,这种简单化的方法是如何不能达到你的某些需求的,因此它可以根据你的实际需要来丰富。在

相关问题 更多 >