![](/img/trans.png)
[英]@decorator get Class.__name__ of @staticmethod and @classmethod
[英]Why can @decorator not decorate a staticmethod or a classmethod?
为什么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。
classmethod
和staticmethod
返回描述符对象,而不是函数。 大多数装饰器并非设计为接受描述符。
通常,当使用多个装饰器时,您必须最后应用classmethod
和staticmethod
。 并且由于装饰器是按“自下而上”的顺序应用的,因此classmethod
和staticmethod
通常应该在您的源代码中最顶层。
像这样:
class My_class(object):
@classmethod
@print_function_name
def get_dir(cls):
return dir(cls)
@staticmethod
@print_function_name
def get_a():
return 'a'
当@classmethod
和@staticmethod
是最顶层的装饰器时,它起作用:
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'
这是你想要的吗?
def print_function_name(function):
def wrapper(*args):
print('%s was called.' % function.__name__)
return function(*args)
return wrapper
class My_class(object):
@classmethod
@print_function_name
def get_dir(cls):
return dir(cls)
@staticmethod
@print_function_name
def get_a():
return 'a'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.