我对装饰者的工作有疑问。我想用一个例子装饰者的工作
我实现了解装饰
import sys
import inspect
def entryExit(f):
def new_f(self,*args, **kwargs):
print "Entering", f.__name__,self.__class__.__name__,inspect.getargspec(f).args[1:]
f(self,*args)
print "Exited", f.__name__,self.__class__.__name__,inspect.getargspec(f).args[1:]
return new_f
class A:
@entryExit
def move(self,g,h):
print "hello"
print g,h
@entryExit
def move1(self,m,n):
print "hello"
print m,n
return m
a=A()
a.move(5,7)
h=a.move1(3,4)
print h
这段代码的输出代码解释我的问题是
Entering move A ['g', 'h']
hello
5 7
Exited move A ['g', 'h']
Entering move1 A ['m', 'n']
hello
3 4
Exited move1 A ['m', 'n']
None
输出显示None
的最后一道防线。但是通过使用装饰器来改变方法的实际含义。没有执行方法move1
中的返回语句。实际输出的,我需要将
Entering move A ['g', 'h']
hello
5 7
Exited move A ['g', 'h']
Entering move1 A ['m', 'n']
hello
3 4
Exited move1 A ['m', 'n']
3
所以我才犯任何错误,而总是创建装饰或装修忽略函数返回语句?
装饰者*只是功能*,所以你需要像对待任何其他链接函数调用.. – 2013-03-14 15:20:20