为什么@decorator不能修饰staticmethod或classmethod?

2024-04-29 15:25:28 发布

您现在位置:Python中文网/ 问答频道 /正文

为什么decorator不能修饰staticmethod或classmethod?

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'

get_dirget_a都会导致AttributeError: <'classmethod' or 'staticmethod'>, object has no attribute '__name__'

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

编辑:我正在使用Python2.6。


Tags: namegetreturn属性objectdefdirargs
3条回答

@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'

classmethodstaticmethod返回descriptor objects,不是函数。大多数装饰器的设计不是为了接受描述符。

通常,在使用多个decorator时,必须最后应用classmethodstaticmethod。而且由于decorator是按“自底向上”的顺序应用的,所以classmethodstaticmethod通常应该是源代码中最上面的。

像这样:

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

    @staticmethod
    @print_function_name
    def get_a():
        return 'a'

这是你想要的吗?

def print_function_name(function):
    def wrapper(*args):
        print('%s was called.' % function.__name__)
        return function(*args)
    return wrapper

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

    @staticmethod
    @print_function_name
    def get_a():
        return 'a'

相关问题 更多 >