【Python面向对象】(6) 装饰器(decorator)
1. 用于拓展原来函数功能的一种函数
2. 返回函数的一种函数
3. 在不用更改原函数代码的前提下给函数添加新的的功能
(1)没有装饰器时的实现
"""
不用装饰器的情况
"""
def hello():
print("hello...")
def test():
print("test...")
def hello_wrapper():
print("开始hello函数...")
hello()
print("结束hello函数...")
def test_wrapper():
print("开始test函数...")
test()
print("结束test函数...")
if __name__ == "__main__":
# 其实这两个函数的构造都差不多,但是分为了两个方法来书写,代码的重用度不够
hello_wrapper()
# 输出:
# 开始hello函数...
# hello...
# 结束hello函数...
test_wrapper()
# 输出:
# 开始test函数...
# test...
# 结束test函数...(2)装饰器下的实现
"""
用装饰器实现
"""
def log_in(func):
""" 记录操作日志(英文) """
def wrapper():
print("start...")
func()
print("end...")
return wrapper
def log_out(func):
""" 记录操作日志(中文) """
def wrapper():
print("开始执行...")
func()
print("结束执行...")
return wrapper
# 使用1个装饰器
@log_in
def hello():
print("hello...")
# 使用2个装饰器
@log_out
@log_in
def test():
print("test...")
if __name__ == "__main__":
hello()
# 输出:
# start...
# hello...
# end...
test()
# 输出:
# 开始执行...
# start...
# test...
# end...
# 结束执行... 相关推荐
敏敏张 2020-11-11
SCNUHB 2020-11-10
小木兮子 2020-11-11
WasteLand 2020-10-18
Cocolada 2020-11-12
杜鲁门 2020-11-05
shirleypaddy 2020-10-19
qingmumu 2020-10-19
Testingba工作室 2020-09-15
周公周金桥 2020-09-13
专注前端开发 2020-08-16
emagtestage 2020-08-16
heniancheng 2020-08-15
hanjinixng00 2020-08-12
小方哥哥 2020-08-09
83327712 2020-07-30
卖小孩的咖啡 2020-07-21
wqiaofujiang 2020-07-05