繁体   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