Почему @decorator не может украсить staticmethod или classmethod?

Почему может 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_dir и get_a результат в AttributeError: <'classmethod' or 'staticmethod'>, object has no attribute '__name__'.

Почему делает decorator полагайтесь на атрибут __name__ вместо атрибута func_name? (Afaik все функции, включая classmethods и staticmethods, имеют func_name атрибут.)

Править: Я использую Python 2.6.

32
задан Nathaniel Jones 11 January 2019 в 19:27
поделиться

2 ответа

Работает, когда @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'
26
ответ дан 27 November 2019 в 20:00
поделиться

Это то, что вы хотели?

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'
2
ответ дан 27 November 2019 в 20:00
поделиться
Другие вопросы по тегам:

Похожие вопросы: