目标:使装饰类方法成为可能。当一个类方法被修饰时,它被存储在字典中,以便其他类方法可以通过字符串名引用它。在
动机:我想实现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"
可能还有别的办法。我很乐意接受建议
这是不必要的。只需使用
getattr
:唯一需要注意的是,您必须确保只有打算用作webmethods的方法才能这样使用。IMO最简单的解决方案是采用一种约定,即非webmethods以下划线开头,并让
post
方法拒绝服务此类名称。在如果您真的想使用装饰器,请尝试以下方法:
^{pr2}$并在调用方法之前让
post
检查is_webmethod
属性是否存在。在这似乎是满足您所述规格的最简单方法:
而且,在
^{pr2}$WebmethodBaseClass
中我怀疑你想要不同的东西(例如,不同子类的单独名称空间与单个全局
webmethods
字典…?),但如果没有更多的信息,很难猜测你的欲望与你的规格有什么不同,所以也许你可以告诉我们,这种简单化的方法是如何不能达到你的某些需求的,因此它可以根据你的实际需要来丰富。在相关问题 更多 >
编程相关推荐