我有一个关于装修工工作的问题。我想用一个例子来解释我的问题
我实现的用来理解装饰器的代码
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
。但是这个方法的实际意义是通过使用decorators来改变的。方法move1
中的return语句未执行。我需要的实际输出是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
所以我在创建decorator时是否犯了什么错误,或者decorators总是忽略函数中的return语句?
最佳答案
问题是decorator丢弃修饰函数的返回值。
以下内容:
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:]
应改为:
def new_f(self,*args, **kwargs):
print "Entering", f.__name__,self.__class__.__name__,inspect.getargspec(f).args[1:]
ret = f(self,*args)
print "Exited", f.__name__,self.__class__.__name__,inspect.getargspec(f).args[1:]
return ret
当前代码忽略
f(self,*args)
的返回值,并隐式返回None
。关于python - 装饰器的工作,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/15413188/