def site_catch_error(func):
def _deco(*arg, **karg):
try:
return func(*arg, **karg)
except Exception,e:
print 'error:',e
return []
return _deco
def catch_err_ret(*args,**kwargs):
def _exec(func):
def make_decorater(*args1,**kwargs1):
#print(args,kwargs)
#print(args1,kwargs1)
try:
return func(*args1,**kwargs1)
except Exception,e:
print e
#print type(args)
if len(args) > 0:
return args if len(args)>1 else args[0]
if kwargs is not None \
and kwargs != {}:
return kwargs
return False
return make_decorater
return _exec
@catch_err_ret(1,2,3)
def test1(data=""):
print "aaa",data
raise Exception("error!")
return 1,2,3
# 使用装饰函数在函数执行前和执行后分别附加额外功能
# -*- coding:gbk -*-
'''示例2: 替换函数(装饰)
装饰函数的参数是被装饰的函数对象,返回原函数对象
装饰的实质语句: myfunc = deco(myfunc)'''
def deco(func):
print("before myfunc() called.")
func()
print(" after myfunc() called.")
return func
def myfunc():
print(" myfunc() called.")
myfunc = deco(myfunc)
myfunc()
myfunc()
# 使用语法糖@来装饰函数
# -*- coding:gbk -*-
'''示例3: 使用语法糖@来装饰函数,相当于“myfunc = deco(myfunc)”
但发现新函数只在第一次被调用,且原函数多调用了一次'''
def deco(func):
print("before myfunc() called.")
func()
print(" after myfunc() called.")
return func
@deco
def myfunc():
print(" myfunc() called.")
myfunc()
myfunc()