python 为什么@decorator 不能装饰静态方法或类方法?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1987919/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Why can @decorator not decorate a staticmethod or a classmethod?
提问by user238424
Why can decoratornot 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'
Both get_dirand get_aresult in AttributeError: <'classmethod' or 'staticmethod'>, object has no attribute '__name__'.
双方get_dir并get_a导致AttributeError: <'classmethod' or 'staticmethod'>, object has no attribute '__name__'。
Why does decoratorrely on the attribute __name__instead of the attribute func_name? (Afaik all functions, including classmethods and staticmethods, have the func_nameattribute.)
为什么decorator依赖属性__name__而不是属性func_name?(Afaik 所有函数,包括 classmethods 和 staticmethods,都具有该func_name属性。)
Edit: I'm using Python 2.6.
编辑:我使用的是 Python 2.6。
采纳答案by user238424
It works when @classmethodand @staticmethodare the top-most decorators:
当@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'
回答by wberry
classmethodand staticmethodreturn descriptor objects, not functions. Most decorators are not designed to accept descriptors.
classmethod并staticmethod返回描述符对象,而不是函数。大多数装饰器并非设计为接受描述符。
Normally, then, you must apply classmethodand staticmethodlast when using multiple decorators. And since decorators are applied in "bottom up" order, classmethodand staticmethodnormally should be top-most in your source.
通常,当使用多个装饰器时,您必须 applyclassmethod和staticmethodlast。并且由于装饰器以“自下而上”的顺序应用,classmethod并且staticmethod通常应该在您的源代码中最顶层。
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'
回答by mykhal
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'

