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

Discussão em 'Python' iniciado por Stack, Maio 29, 2025.

  1. Stack

    Stack Membro Participativo

    Why can decorator not decorate a staticmethod or a classmethod in Python 2.6?

    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'


    Both get_dir and get_a result in AttributeError: <'classmethod' or 'staticmethod'>, object has no attribute '__name__'.

    Why does decorator rely on the attribute __name__ instead of the attribute func_name? (Afaik all functions, including classmethods and staticmethods, have the func_name attribute.)

    Continue reading...

Compartilhe esta Página