我想创建一个Python 类装饰器(*),它将能够无缝地包装类可能具有的所有方法类型:实例,类和静态。如何创建一个能够包装实例,类和静态方法的Python类装饰器?
这是我对现在的代码,与打破它注释的部分:
def wrapItUp(method):
def wrapped(*args, **kwargs):
print "This method call was wrapped!"
return method(*args, **kwargs)
return wrapped
dundersICareAbout = ["__init__", "__str__", "__repr__"]#, "__new__"]
def doICareAboutThisOne(cls, methodName):
return (callable(getattr(cls, methodName))
and (not (methodName.startswith("__") and methodName.endswith("__"))
or methodName in dundersICareAbout))
def classDeco(cls):
myCallables = ((aname, getattr(cls, aname)) for aname in dir(cls) if doICareAboutThisOne(cls, aname))
for name, call in myCallables:
print "*** Decorating: %s.%s(...)" % (cls.__name__, name)
setattr(cls, name, wrapItUp(call))
return cls
@classDeco
class SomeClass(object):
def instanceMethod(self, p):
print "instanceMethod: p =", p
@classmethod
def classMethod(cls, p):
print "classMethod: p =", p
@staticmethod
def staticMethod(p):
print "staticMethod: p =", p
instance = SomeClass()
instance.instanceMethod(1)
#SomeClass.classMethod(2)
#instance.classMethod(2)
#SomeClass.staticMethod(3)
#instance.staticMethod(3)
我有两个问题想使这项工作:
- 当遍历所有可以调用,我怎么知道它是一个实例,类还是静态类型?
- 如何使用正确调用的正确包装版本覆盖该方法,并为每种情况正确调用?
目前,该代码会生成不同TypeError
小号根据什么评论片段是未加注释,如:
TypeError: unbound method wrapped() must be called with SomeClass instance as first argument (got int instance instead)
TypeError: classMethod() takes exactly 2 arguments (3 given)
(*):同问题要简单得多,如果你是decorating the methods directly。
看到不同的开发人员如何处理这个相同的,复杂的问题将会很有趣。 – wberry
@wberry:是的,我已经阅读了当前的答案,并且发现很难选择“正确”的答案。 – Chuim