本篇文章为大家展示了如何在Python中定义装饰器,内容简明扼要并且容易理解,绝对能使你眼前一亮,通过这篇文章的详细介绍希望你能有所收获。
Python 装饰器
一、何为装饰器
1、在函数中定义函数
在函数中定义另外的函数,就是说可以创建嵌套的函数,例子如下
def sayHi(name="hjj2"):
print 'inside sayHi() func'
def greet():
return 'inside greet() func'
print(greet())
sayHi()
#output
# inside sayHi() func
# inside greet() func
2、将函数作为参数传给另外一个函数,装饰器原型
def sayHi():
return 'hi hjj2'
def doSthBeforeSayHi(func):
print 'before sayHi func'
print(func())
doSthBeforeSayHi(sayHi)
#output
# before sayHi func
# hi hjj2
3、实现一个装饰器
在第二步中,我们已经基本探究到装饰器的原理了,python装饰器做的事就是通过封装一个函数并且用这样或那样的方式来修改它的行为。不带@的初步示例如下:
def new_decorator(func):
def wrapDecorator():
print 'before func'
func()
print 'after func'
return wrapDecorator
def func_require_decorator():
print 'a func need decorator'
func_require_decorator()
#ouput: a func need decorator
func_require_decorator = new_decorator(func_require_decorator)
func_require_decorator()
#ouput:
# before func
# a func need decorator
# after func
使用@来运行装饰器
@new_decorator
func_require_decorator()
#ouput:
# before func
# a func need decorator
# after func
这里我们可以看到,这两个例子的运行结果是一样的。所以我们能想象得到@new_decorator的作用就是
func_require_decorator = new_decorator(func_require_decorator)
我们继续优化这个装饰器,现在我们有一个问题就是,如果我们想要通过print(func_require_decorator.__name__)
就会报错# Output: wrapTheFunction。这样就需要借助python提供的functools.wraps
来解决了
@wraps接受一个函数来进行装饰,并加入了复制函数名称、注释文档、参数列表等等的功能。这可以让我们在装饰器里面访问在装饰之前的函数的属性。
from functools import wraps
def new_decorator(func):
@wraps(func)
def wrapDecorator():
print 'before func'
func()
print 'after func'
return wrapDecorator
def func_require_decorator():
print 'a func need decorator'
@new_decorator
func_require_decorator()
print(func_require_decorator.__name__)
#ouput: func_require_decorator
二、使用场景
1、授权,大体例子
from functools import wraps
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()
return f(*args, **kwargs)
return decorated
2、日志:
from functools import wraps
def logit(logfile='out.log'):
def logging_decorator(func):
@wraps(func)
def wrapped_function(*args,**kwargs):
log_string = func.__name__+"was called"
print(log_string)
with open(logfile,'a') as opened_file:
opened_file.write(log_string+'\n')
return func(*args,**kwargs)
return wrapped_function
return logging_decorator
@logit()
def func1():
pass
func1()
3、其他如flask中的@app.route()
三、装饰器类
1、将上面的日志装饰器变为类的初步模型如下
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 open_file:
# 将日志写到指定文件
open_file.write(log_string + '\n')
# 发送一个通知
self.notify()
return func(*args, **kwargs)
return wrapped_function
def notify(self):
pass
@logit()
def myfunc1():
pass
class email_logit(logit):
'''
实现在函数调用时发送email
'''
def __init__(self, email='admin@xxx.com', *args, **kwargs):
self.email = email
super(email_logit, self).__init__(*args, **kwargs)
def notify(self):
'''
发送邮件通知
'''
pass
python的数据类型:1. 数字类型,包括int(整型)、long(长整型)和float(浮点型)。2.字符串,分别是str类型和unicode类型。3.布尔型,Python布尔类型也是用于逻辑运算,有两个值:True(真)和False(假)。4.列表,列表是Python中使用最频繁的数据类型,集合中可以放任何数据类型。5. 元组,元组用”()”标识,内部元素用逗号隔开。6. 字典,字典是一种键值对的集合。7. 集合,集合是一个无序的、不重复的数据组合。
上述内容就是如何在Python中定义装饰器,你们学到知识或技能了吗?如果还想学到更多技能或者丰富自己的知识储备,欢迎关注亿速云行业资讯频道。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。