【发布时间】:2010-12-31 13:39:55
【问题描述】:
为什么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__'。
为什么decorator 依赖属性__name__ 而不是属性func_name? (Afaik 所有函数,包括 classmethods 和 staticmethods,都具有 func_name 属性。)
编辑:我使用的是 Python 2.6。
【问题讨论】:
-
你为什么在装饰器内部调用函数(*args)?它的工作是简单地返回一个函数(在你的情况下,未修改)。
-
gahooa:因为这是“装饰器”(他导入的内容,而不是语言结构)的一种工作方式,请参阅pypi.python.org/pypi/decorator。
-
@taldor 你在 py 2.6 中有装饰器模块吗?
-
@mykhal:我单独安装的。