读书人

decorator 兑现 记录函数入口出口及变

发布时间: 2012-12-26 14:39:28 作者: rapoo

decorator 实现 记录函数入口出口及变量值

decorator
A function returning another function, usually applied as a function transformation
using the @wrapper syntax. Common examples for decorators are classmethod() and staticmethod().

The decorator syntax is merely syntactic sugar,
the following two function definitions are semantically equivalent:

def f(...):
...
f = staticmethod(f)

@staticmethod
def f(...):
...
See the documentation for function definition for more about decorators.

###########################################################################
def logMethodEntryExit(funcToLog):
def loggedFunc(*args):
if len(args) >= 1: #__init__(<Recover.CResumeBrokenExecution instance at 0x015A1F58>,)
instanceSelf, argsRest = args[0], args[1:]

metaClassName = str(instanceSelf.__class__).split("'")
if len(metaClassName) == 3:
myName = metaClassName[1]
else:
myName = str(instanceSelf.__class__)

print("===> {0}.{1}{2}".format(myName, funcToLog.__name__, argsRest))
else:
print("===> {0}{1}".format(funcToLog.__name__, args))

#return funcToLog(*args)
resultCache = funcToLog(args[0], * args[1:])
print("<=== return: {0}".format(resultCache))

def surrogateFunc(* args):
return resultCache
return surrogateFunc(* args)

return loggedFunc

if __name__ == "__main__":

class payroll:

@logMethodEntryExit
def tax(self, pretax):
afterTax=7800
return afterTax,'oh my god!'

jan = payroll()
jan.tax(10000)


>>>
===> __main__.payroll.tax(10000,)
<=== return: (7800, ' my god!')

读书人网 >编程

热点推荐