标签:一个 ret 并且 ffffff else ant mil space normal
def get_animal(name=‘dog‘):
def dog():
return ‘this is a dog‘
def cat():
return ‘this is a cat‘
# 返回函数对象
if name == ‘dog‘:
return dog
elif name == ‘cat‘:
return cat
else:
return ‘other animal‘
animal = get_animal(‘cat‘)
print(animal) # <function get_animal.<locals>.cat at 0x104b30d90>
print(animal())
def my_decorator(a_function_to_decorate):
def wapper_function(*args, **kwargs):
print(‘Before the function runs‘)
a_function_to_decorate(*args, **kwargs)
print(‘After the function runs‘)
return wapper_function
@my_decorator
def stand_function():
print(‘stand function runs‘)
stand_function()
# "functools" 可以改变这点
import functools
def bar(func):
@functools.wraps(func)
def wrapper():
return func()
return wrapper
import logging, time
def create_logger():
logger = logging.getLogger("example_logger")
logger.setLevel(logging.INFO)
# create the logging file handler
handler = logging.FileHandler(r"./test.log")
formatter = logging.Formatter(‘%(asctime)s - %(name)s - %(levelname)s - %(message)s‘)
handler.setFormatter(formatter)
# add handler to logger object
logger.addHandler(handler)
return logger
def exception(logger):
def decorator(func):
def wrapper(*args, **kwargs):
start = time.time()
try:
logger.info(‘function runs‘)
res = func(*args, **kwargs)
print(‘the function used time: {}‘.format(time.time()-start))
logger.info(‘function stops‘)
return res
except:
# log the exception
err = "There was an exception in "
err += func.__name__
logger.exception(err)
raise Exception
return wrapper
return decorator
logger = create_logger()
@exception(logger=logger)
def foo(name=‘foo_function‘):
print(‘i am {}‘.format(name))
return True
print(foo())
标签:一个 ret 并且 ffffff else ant mil space normal
原文地址:http://www.cnblogs.com/George1994/p/7362379.html