相关疑难解决方法(0)

为什么@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'
Run Code Online (Sandbox Code Playgroud)

双方get_dirget_a导致AttributeError: <'classmethod' or 'staticmethod'>, object has no attribute '__name__'.

为什么decorator依赖属性__name__而不是属性func_name?(Afaik所有函数,包括classmethods和staticmethods,都有func_name属性.)

编辑:我正在使用Python 2.6.

python decorator

32
推荐指数
2
解决办法
1万
查看次数

标签 统计

decorator ×1

python ×1