Why can @decorator not decorate a staticmethod or a classmethod?

后端 未结 3 1645
萌比男神i
萌比男神i 2020-12-01 03:35

Why can decorator not decorate a staticmethod or a classmethod?

from decorator import decorator

@decorator
def print_function_name(function, *a         


        
相关标签:
3条回答
  • 2020-12-01 03:59

    Is this what you wanted?

    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'
    
    0 讨论(0)
  • 2020-12-01 04:00

    It works when @classmethod and @staticmethod are the top-most decorators:

    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'
    
    0 讨论(0)
  • 2020-12-01 04:21

    classmethod and staticmethod return descriptor objects, not functions. Most decorators are not designed to accept descriptors.

    Normally, then, you must apply classmethod and staticmethod last when using multiple decorators. And since decorators are applied in "bottom up" order, classmethod and staticmethod normally should be top-most in your source.

    Like this:

    class My_class(object):
        @classmethod
        @print_function_name
        def get_dir(cls):
            return dir(cls)
    
        @staticmethod
        @print_function_name
        def get_a():
            return 'a'
    
    0 讨论(0)
提交回复
热议问题