为什么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_dir
并get_a
导致AttributeError: <'classmethod' or 'staticmethod'>, object has no attribute '__name__'
.
为什么decorator
依赖属性__name__
而不是属性func_name
?(Afaik所有函数,包括classmethods和staticmethods,都有func_name
属性.)
编辑:我正在使用Python 2.6.
wbe*_*rry 62
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'
Run Code Online (Sandbox Code Playgroud)
use*_*424 26
它的工作原理时,@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'
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
10633 次 |
最近记录: |