python代码:高级闭包和装饰器的例子
#!/usr/bin/python
# -*- coding: UTF-8 -*-
"""
@author:
@file:funcLog.py
@time:2022-04-03 20:37
"""
# 书《Python核心编程(第二版).pdf》,作者:Wesley J. Chun
# 例子:高级闭包和装饰器的例子
# 应用程序logs函数调用。
# 用户选择是要在函数调用之前或者之后,把函数调用写入日志。如果选择贴日志,执行时间也会显示出来。
# 这个例子演示了带参数的装饰器,该参数最终决定哪一个闭包会被调用的。这也是闭包的威力的特征。
# from time import time
import time
def logged(when):
print("The value of when: ", when)
def log(f, *args, **kargs):
print('''Called:
function: %s
args: %r
kargs: %r''' % (f, args, kargs))
time.sleep(1) # 因为电脑运行的速度太快了,统计程序运行的时间总是0,所以人为延迟1秒,从而使运行时间不为0.
def pre_logged(f):
def wrapper(*args, **kargs):
log(f, *args, **kargs)
return f(*args, **kargs)
return wrapper
def post_logged(f):
def wrapper(*args, **kargs):
# now = time()
now = time.time()
try:
return f(*args, **kargs)
finally:
log(f, *args, **kargs)
# print("time delta: %s" % (time() - now))
print("time delta: %s" % (time.time() - now))
return wrapper
try:
# # 解释:{...}里的东东为字典,[...]里的东东为字典的键key。连在一起看,就是返回字典中指定key对应的value。
# # 所以那一行return {...}[...]代码等价于以下几行代码:
# dict_return = {"pre": pre_logged, "post": post_logged}
# key_return = when
# return dict_return[key_return]
return {"pre": pre_logged,
"post": post_logged}[when]
except KeyError as e:
# print(type(e)) # <class 'KeyError'>
# print(e) # 'wrong'
# print(repr(e)) # KeyError('wrong')
raise ValueError(repr(e), 'must be "pre" or "post"') # ValueError: (KeyError('wrong'), 'must be "pre" or "post"')
# @logged("pre") # 装饰器 # 等同于: hello = logged("pre")(hello("world!"))
@logged("post") # 装饰器 # 等同于: hello = logged("post")(hello("world!"))
# @logged("wrong") # 装饰器 # 等同于: hello = logged("wrong")(hello("world!"))
def hello(name):
print("Hello,", name)
if __name__ == "__main__":
hello("World!")
"""
当装饰器是@logged("pre")时,输出结果如下:
The value of when: pre
Called:
function: <function hello at 0x000001E82EF36550>
args: ('World!',)
kargs: {}
Hello, World!
----
当装饰器是@logged("post")时,输出结果如下:
The value of when: post
Hello, World!
Called:
function: <function hello at 0x0000022DDF5CB9D0>
args: ('World!',)
kargs: {}
time delta: 1.002335786819458
----
当装饰器是@logged("wrong")时,输出结果如下:
Traceback (most recent call last):
File "E:\workspace\PycharmProjects\project01\com\study\pythoncore\ch02\funcLog.py", line 50, in logged
return {"pre": pre_logged,
KeyError: 'wrong'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "E:\workspace\PycharmProjects\project01\com\study\pythoncore\ch02\funcLog.py", line 58, in <module>
@logged("wrong") # 装饰器 # 等同于: hello = logged("wrong")(hello("world!"))
File "E:\workspace\PycharmProjects\project01\com\study\pythoncore\ch02\funcLog.py", line 56, in logged
raise ValueError(repr(e), 'must be "pre" or "post"') # ValueError: (KeyError('wrong'), 'must be "pre" or "post"')
ValueError: ("KeyError('wrong')", 'must be "pre" or "post"')
The value of when: wrong
Process finished with exit code 1
"""
|