How to apply a python decorator to a function?
本问题已经有最佳答案,请猛点这里访问。
Possible Duplicate:
Understanding Python decorators
你能给我一个解释装饰师的简短代码示例吗?
1 2 3 4 5 6 7 8 9 | def spam(func): def wrapped(*args, **kwargs): print"SPAM" return func(*args, **kwargs) return wrapped @spam #this is the same as doing eggs = spam(eggs) def eggs(): print"Eggs?" |
注意,您还可以使用类来编写修饰符
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | class Spam(object): def __init__(self, func): self.func = func def __repr__(self): return repr(self.func) def __call__(self, *args, **kwargs): print"SPAM" return self.func(*args, **kwargs) @Spam def something(): pass |
decorator接受函数定义并创建一个执行此函数的新函数函数并转换结果。
1 2 3 | @deco def do(): ... |
相当于:
1 | do = deco(do) |
例子:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | def deco(func): def inner(letter): return func(letter).upper() #upper return inner # return a function object #This @deco def do(number): return chr(number) # number to letter #end # is equivalent to this def do2(number): return chr(number) do2 = deco(do2) #end # 65 <=> 'a' print(do(65)) print(do2(65)) >>> B >>> B |
为了理解decorator,需要注意的是decorator创建了一个新的函数do,它是内部函数,执行func并转换结果。