[python]代码库
from functools import wraps
import time
import datetime
class TimeIt:
def __init__(self,fn,):
print('init')
self._fn = fn
# self.__doc__ = self._fn.__doc__
# self.__name__ = self._fn.__name__
wraps(self._fn)(self)
def __enter__(self):
print('enter')
self.start = datetime.datetime.now()
return self
def __exit__(self, exc_type, exc_val, exc_tb):
print('exit')
self.delta = (datetime.datetime.now()-self.start).total_seconds()
print('context {} took {}'.format(self._fn.__name__,self.delta))
return
def __call__(self, *args,**kwargs):
print('__call__')
return self._fn(*args,**kwargs)
def logger(fn):
@wraps(fn) # wrapper = wraps(fn)(wrapper)
def wrapper(*args,**kwargs):
start = datetime.datetime.now()
ret = fn(*args,**kwargs)
delta = (datetime.datetime.now() - start).total_seconds()
print('dec {} took {}'.format(fn.__name__,delta))
return ret
return wrapper
@TimeIt
def add(x,y): # add = TimeIt(add)
"""This is a function~~~~~~~"""
time.sleep(2)
return x + y
print(add(5,10))
print(add.__doc__)
print(add.__name__)
print(add.__dict__)
print(type(add))