为什么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
属性。)
编辑:我正在使用Python2.6。
当
@classmethod
和@staticmethod
是最顶级的装饰器时,它就工作了:classmethod
和staticmethod
返回descriptor objects,不是函数。大多数装饰器的设计不是为了接受描述符。通常,在使用多个decorator时,必须最后应用
classmethod
和staticmethod
。而且由于decorator是按“自底向上”的顺序应用的,所以classmethod
和staticmethod
通常应该是源代码中最上面的。像这样:
这是你想要的吗?
相关问题 更多 >
编程相关推荐