python3.3 装饰器日志

#!/usr/local/bin/Python3.3
#-*-coding:utf-8-*-

def log_none_params(func):
	'''
	none params decorate function
	'''
	def log(*args, **kargs):
		print("before func" + str(func))
		try:
			return func(*args, **kargs);
		finally:
			print("after func")
	return log	
	
def log_with_params(when):
	'''
	log decorate function with params 
	'''

	def pre_log(func, *args, **kargs):
		def log():
			print("pre_log ...")
			return func(*args, **kargs);
		return log
	
	def sub_log(func, *args, **kargs):
		def log():
			try:
				return func(*args, **kargs)
			finally:
				print("sub_log ...")
		return log

	try:
		return {"pre":pre_log, "sub":sub_log}[when]
	except:
		print("when must in (pre, sub)")


@log_none_params
def test_method1():
	print("in test_method1")
	
@log_with_params("sub")	
def test_method2():
	print("in test_method2...")		
	
if __name__ == '__main__':
	test_method1()
	test_method2()

你可能感兴趣的:(python)