decorator
为什么不装饰静态方法或类方法?为什么@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'
两个get_dir
和get_a
结果AttributeError: <'classmethod' or 'staticmethod'>, object has no attribute '__name__'
。
为什么在属性__name__
而不是属性func_name
依赖decorator
? (Afaik的所有功能,包括类方法和静态方法,都具有func_name
属性。)
编辑:我正在使用Python 2.6。
内部装饰你为什么要调用函数(*参数)?它的工作就是简单地返回一个函数(在你的情况下,未修改)。 – gahooa 2010-01-01 05:22:17
gahooa:因为这是“装饰者”(他输入的内容,而不是语言结构)的一种方式,请参阅http://pypi.python.org/pypi/decorator。 – 2010-01-01 06:28:24
@taldor你有装饰模块在Python 2.6? – mykhal 2010-01-04 10:41:55