繁体   English   中英

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

[英]Why can @decorator not decorate a staticmethod or a classmethod?

为什么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'

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

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

编辑:我使用的是 Python 2.6。

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

通常,当使用多个装饰器时,您必须最后应用classmethodstaticmethod 并且由于装饰器是按“自下而上”的顺序应用的,因此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'

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

这是你想要的吗?

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'

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM