为什么@decorator不能装饰静态方法或类方法?

use*_*424 32 python decorator

为什么decorator不能装饰静态方法或类方法呢?

from decorator import decorator

@decorator
def print_function_name(function, *args):
    print '%s was called.' % function.func_name
    return function(*args)

class My_class(object):
    @print_function_name
    @classmethod
    def get_dir(cls):
        return dir(cls)

    @print_function_name
    @staticmethod
    def get_a():
        return 'a'
Run Code Online (Sandbox Code Playgroud)

双方get_dirget_a导致AttributeError: <'classmethod' or 'staticmethod'>, object has no attribute '__name__'.

为什么decorator依赖属性__name__而不是属性func_name?(Afaik所有函数,包括classmethods和staticmethods,都有func_name属性.)

编辑:我正在使用Python 2.6.

wbe*_*rry 62

classmethodstaticmethod返回描述符对象,而不是函数.大多数装饰器不是为接受描述符而设计的.

通常情况下,您必须在使用多个装饰器时应用classmethodstaticmethod持续使用.并且由于装饰器以"自下而上"的顺序应用,classmethod并且staticmethod通常应该是源中最顶层的.

像这样:

class My_class(object):
    @classmethod
    @print_function_name
    def get_dir(cls):
        return dir(cls)

    @staticmethod
    @print_function_name
    def get_a():
        return 'a'
Run Code Online (Sandbox Code Playgroud)


use*_*424 26

它的工作原理时,@classmethod@staticmethod是最顶端的装饰:

from decorator import decorator

@decorator
def print_function_name(function, *args):
    print '%s was called.' % function.func_name
    return function(*args)

class My_class(object):
    @classmethod
    @print_function_name
    def get_dir(cls):
        return dir(cls)
    @staticmethod
    @print_function_name
    def get_a():
        return 'a'
Run Code Online (Sandbox Code Playgroud)

  • 作为一项规则,`classmethod`和`staticmethod`应用了一种特殊的魔法,必须在最后调用. (9认同)