为什么@decorator无法修饰静态方法或类方法? [英] Why can @decorator not decorate a staticmethod or a classmethod?

查看:63
本文介绍了为什么@decorator无法修饰静态方法或类方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么装饰器不装饰静态方法或类方法?

Why can decorator not decorate a staticmethod or a 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'或'staticmethod'> ;,对象没有属性'__name __'

为什么装饰器依赖属性 __ name __ 而不是属性 func_name ? (Afaik的所有函数(包括类方法和静态方法)都具有 func_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.)

编辑:我正在使用Python 2.6。

I'm using Python 2.6.

推荐答案

@classmethod 和<$ c时有效$ c> @staticmethod 是最顶级的装饰器:

It works when @classmethod and @staticmethod are the top-most decorators:

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'

这篇关于为什么@decorator无法修饰静态方法或类方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆