装饰器函数和装饰器类

1.装饰器函数就是把函数作为参数传给一个函数

# def a_new_decorater(a_func):
# def wrapTheFunction():
# print("I am doing some boring work before executing a_func()")
# a_func()
# print("I am doing some boring work after executing a_func()")
# return wrapTheFunction
# def a_function_requiring_decoration():
# print("I am the function which needs some decoration to remove my foul smell")
# a_function_requiring_decoration()
# a_function_requiring_decoration = a_new_decorater(a_function_requiring_decoration)
# a_function_requiring_decoration()
# @a_new_decorater
# def a_function_requiring_decoration():
# """Hey you!Decorate me!"""
# print("I am the function which needs some decoration to" "remove my foul smell")
# a_function_requiring_decoration()
#
# a_function_requiring_decoration = a_new_decorater(a_function_requiring_decoration)
from functools import wraps
# def a_new_decorator(a_func):
# @wraps(a_func)
# def wrapTheFunction():
# print("I am doing some boring work before executing a_func()")
# a_func
# print("I am doing some boring work after executing a_func()")
# return wrapTheFunction
# @a_new_decorator
# def a_function_requiring_decoration():
# """Hey yo!Decorate me!"""
# print("I am the function which needs some decoration to" "remove my foul smell")
# print(a_function_requiring_decoration.__name__)
# def decorator_name(f):
# @wraps(f)
# def decorated(*args,**kwargs):
# if not can_run:
# return "Function will not run"
# return f(*args,**kwargs)
# return decorated
# @decorator_name
# def fun():
# return ("Function is running")
# can_run = True
# print(fun())
# can_run = False
# print(fun())
#认证
# def requires_auth(f):
# @wraps(f)
# def decorated(*args,**kwargs):
# auth = request.authorization
# if not auth or not check_auth(auth.username,auth.password):
# authenticate(0)
# return f(*args,**kwargs)
# return decorated
#日志
from functools import wraps
# def logit(func):
# @wraps(func)
# def with_logging(*args,**kwargs):
# print(func.__name__ + "was called")
# return func(*args, **kwargs)
# return with_logging
# @logit
# def addition_func(x):
# """DO some math."""
# return x + x
# result = addition_func(4)
# print(result)
#一个类实例也可以变成一个可调用对象,只需要实现一个特殊方法__call__()。
from functools import wraps

class logit(object):
def __init__(self, logfile='out.log'):
self.logfile = logfile

def __call__(self, func):
@wraps(func)
def wrapped_function(*args, **kwargs):
log_string = func.__name__ + " was called"
print(log_string)
# 打开logfile并写入
with open(self.logfile, 'a') as opened_file:
# 现在将日志打到指定的文件
opened_file.write(log_string + '\n')
# 现在,发送一个通知
self.notify()
return func(*args, **kwargs)
return wrapped_function

def notify(self):
# logit只打日志,不做别的
pass
# 这个实现有一个附加优势,在于比嵌套函数的方式更加整洁,而且包裹一个函数还是使用跟以前一样的语法:
@logit()
def myfunc1():
pass
# 现在,我们给logit创建子类,来添加email的功能(虽然email这个话题不会在这里展开)。
class email_logit(logit):
'''
一个logit的实现版本,可以在函数调用时发送email给管理员
'''
def __init__(self, email='admin@myproject.com', *args, **kwargs):
self.email = email
super(email_logit, self).__init__(*args, **kwargs)

def notify(self):
# 发送一封email到self.email
# 这里就不做实现了
pass
# 从现在起,@email_logit将会和@logit产生同样的效果,但是在打日志的基础上,还会多发送一封邮件给管理员。

posted on 2017-09-14 09:51  Jt00  阅读(231)  评论(0编辑  收藏  举报

导航