Почему может 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.
Работает, когда @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'