import sys
import time
from public.LogUtils import Logging, colour
def get_now_time():
return time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(time.time()))
class Logging:
flag = True
@staticmethod
def error(msg):
if Logging.flag:
colour.show_error(get_now_time() + " [Error]:" + "".join(msg))
@staticmethod
def warn(msg):
if Logging.flag:
colour.show_warn(get_now_time() + " [Warn]:" + "".join(msg))
@staticmethod
def info(msg):
if Logging.flag:
colour.show_info(get_now_time() + " [Info]:" + "".join(msg))
@staticmethod
def debug(msg):
if Logging.flag:
colour.show_debug(get_now_time() + " [Debug]:" + "".join(msg))
@staticmethod
def success(msg):
if Logging.flag:
colour.show_verbose(get_now_time() + " [Success]:" + "".join(msg))
'''
装饰器:
1、被装饰的函数不带参数的
'''
def decorate01(func):
def inner():
start = time.time()
func()
end = time.time()
print('speed{}'.format(end - start))
return inner
'''
2、被装饰的函数带有参数
*:表示可变; arg:不可变参数; *arg:可变参数; *args:可变元组; **kwargs:可变字典
'''
def drcorate02(func):
def inner(x, y):
t = func(x, y)
filename = str(sys.argv[0]).split('/')[-1].split('.')[0]
Logging.success('{}:{}, return:{}'.format(filename, func.__name__, t))
return inner
'''
3、装饰器带有参数
'''
def drcorate03(arg): # 装饰器的参数,在外面再套一层
def decorate(func): # 被装饰的函数
def inner(x, y): # 被装饰的函数的参数
t = func(x, y)
filename = str(sys.argv[0]).split('/')[-1].split('.')[0]
print('我是带有参数的装饰器:{}'.format(arg))
Logging.success('{}:{}, return:{}'.format(filename, func.__name__, t))
return inner
return decorate
'''
4、类装饰器,依靠类内部的__call__方法,使用@+类名的形式
首先要理解__call__()的用法,__call__()方法使类的实例具有方法的特性
详解见:https://www.jianshu.com/p/e1d95c4e1697?utm_source=oschina-app
class Foo(object):
def __init__(self, func):
self._func = func
def __call__(self):
start_time=time.time()
self._func()
end_time=time.time()
print('spend %s'%(end_time-start_time))
'''
@decorate01
def getAdd01():
return 'asdf'
@drcorate02
def getAdd02(x, y):
return x + y
@drcorate03(arg='parameter')
def getAdd03(x, y):
return x + y
if __name__ == '__main__':
getAdd01()
getAdd02(1, 2)
getAdd03(3, 4)
python的装饰器
最新推荐文章于 2024-03-04 15:55:42 发布