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 decorator
not 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_dir
and get_a
result 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 decorator
rely on the attribute __name__
instead of the attribute func_name
? (Afaik all functions, including classmethods and staticmethods, have the func_name
attribute.)
为什么decorator
依赖属性__name__
而不是属性func_name
?(Afaik 所有函数,包括 classmethods 和 staticmethods,都具有该func_name
属性。)
Edit: I'm using Python 2.6.
编辑:我使用的是 Python 2.6。
采纳答案by user238424
It works when @classmethod
and @staticmethod
are 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
classmethod
and staticmethod
return descriptor objects, not functions. Most decorators are not designed to accept descriptors.
classmethod
并staticmethod
返回描述符对象,而不是函数。大多数装饰器并非设计为接受描述符。
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.
通常,当使用多个装饰器时,您必须 applyclassmethod
和staticmethod
last。并且由于装饰器以“自下而上”的顺序应用,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'