【问题标题】:How to create a Python class decorator that is able to wrap instance, class and static methods?如何创建一个能够包装实例、类和静态方法的 Python 类装饰器?
【发布时间】:2011-11-18 16:10:06
【问题描述】:

我想创建一个 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)

我在尝试完成这项工作时遇到了两个问题:

  • 在遍历所有可调用对象时,如何确定它是实例、类还是静态类型?
  • 如何使用针对每种情况正确调用的正确包装版本覆盖该方法?

目前,此代码会生成不同的TypeErrors,具体取决于已注释的 sn-p 未注释的内容,例如:

  • 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:是的,我已经在阅读当前的答案并注意到很难选择“正确”的答案。

标签: python reflection decorator instrumentation


【解决方案1】:

因为方法是函数的包装器,所以要在类构建后将装饰器应用于类的方法,您必须:

  1. 使用其im_func 属性从方法中提取底层函数。
  2. 装饰函数。
  3. 重新应用包装器。
  4. 用封装的修饰函数覆盖属性。

一旦应用了@classmethod 装饰器,就很难区分classmethod 和常规方法;这两种方法的类型都是instancemethod。但是,您可以检查im_self 属性,看看它是否为None。如果是这样,它是一个常规的实例方法;否则是classmethod。

静态方法是简单的函数(@staticmethod 装饰器只是阻止应用通常的方法包装器)。所以你不必为这些做任何特别的事情,看起来像。

所以基本上你的算法是这样的:

  1. 获取属性。
  2. 它是可调用的吗?如果没有,请继续下一个属性。
  3. 它的类型是types.MethodType吗?如果是这样,它要么是类方法,要么是实例方法。
    • 如果它的im_self是None,它是一个实例方法。通过im_func 属性提取底层函数,对其进行装饰,然后重新应用实例方法:meth = types.MethodType(func, None, cls)
    • 如果它的im_self不是None,它是一个类方法。通过im_func 提取底层函数并装饰它。现在你必须重新应用 classmethod 装饰器,但你不能因为 classmethod() 没有类,所以没有办法指定它将附加到哪个类。相反,您必须使用实例方法装饰器:meth = types.MethodType(func, cls, type)。请注意,这里的type 是实际内置的type。
  4. 如果它的类型不是types.MethodType那么它是一个静态方法或其他非绑定可调用,所以只需装饰它。
  5. 将新属性设置回类。

这些在 Python 3 中有所改变——未绑定的方法是那里的函数,IIRC。无论如何,这可能需要在那里彻底重新考虑。

【讨论】:

  • 选择这个作为答案,因为它清楚地解释了潜在的问题。感谢和抱歉耽搁了这么久!
【解决方案2】:

有一个未记录的函数inspect.classify_class_attrs,它可以告诉你哪些属性是类方法或静态方法。在底层,它使用isinstance(obj, staticmethod) 和isinstance(obj, classmethod) 对静态方法和类方法进行分类。按照该模式,这适用于 Python2 和 Python3:

def wrapItUp(method,kind='method'):
    if kind=='static method':
        @staticmethod
        def wrapped(*args, **kwargs):
            return _wrapped(*args,**kwargs)
    elif kind=='class method':
        @classmethod
        def wrapped(cls,*args, **kwargs):
            return _wrapped(*args,**kwargs)                
    else:
        def wrapped(self,*args, **kwargs):
            return _wrapped(self,*args,**kwargs)                                
    def _wrapped(*args, **kwargs):
        print("This method call was wrapped!")
        return method(*args, **kwargs)
    return wrapped
def classDeco(cls):
    for name in (name
                 for name in dir(cls)
                 if (callable(getattr(cls,name))
                     and (not (name.startswith('__') and name.endswith('__'))
                          or name in '__init__ __str__ __repr__'.split()))
                 ):
        method = getattr(cls, name)
        obj = cls.__dict__[name] if name in cls.__dict__ else method
        if isinstance(obj, staticmethod):
            kind = "static method"
        elif isinstance(obj, classmethod):
            kind = "class method"
        else:
            kind = "method"
        print("*** Decorating: {t} {c}.{n}".format(
            t=kind,c=cls.__name__,n=name))
        setattr(cls, name, wrapItUp(method,kind))
    return cls

@classDeco
class SomeClass(object):
    def instanceMethod(self, p):
        print("instanceMethod: p = {}".format(p))
    @classmethod
    def classMethod(cls, p):
        print("classMethod: p = {}".format(p))
    @staticmethod
    def staticMethod(p):
        print("staticMethod: p = {}".format(p))

instance = SomeClass()
instance.instanceMethod(1)
SomeClass.classMethod(2)
instance.classMethod(2)
SomeClass.staticMethod(3)
instance.staticMethod(3)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-02-03
    • 1970-01-01
    • 2011-06-26
    相关资源
    最近更新 更多