python 装饰器

''' 闭包函数: 1. 函数内部定义的函数 2. 对外部作用域而非全局作用域的引用 !  '''
def x():
r = 1
def y():
print("Test text:{test}".format(test=r))
print("yys")
return y
''' 闭包作用: 1. 自带作用域 2. 延迟计算 '''
from usrlib.urlrequest import urlopen
def urlread(url):
def get():
reutrn urlopen(url).read()
return get
source_html = urlread("https://i.cnblogs.com/EditPosts.aspx?opt=1") # 返回的是get函数地址
print(source_html()) # 执行get函数
''' 装饰器实现:闭包外部函数传入被装饰函数名 '''
''' 多个装饰器装饰一个函数,执行顺序是从下往上 '''
from decorator import decorator
import time
def logging(x):
@decorator def log(func, *args, **kwargs):   start_time = time.time()   func(*args, **kwargs)
end_time = time.time()
print("func 运行时间:{time}".format(time = end_time - start_time))
return log @logging("888") def yy(t): print("Context: hello {}!".format(t)) yy("66")
''' 类装饰器 :返回类的__call__方法 '''
class tt(object):
def __init__(self, func):
self._func = func
def __call__(self):
self._func()
@tt # mm = tt(mm)
def mm():
print('ss')
class aa(object):
def __init__(self):
pass
def __call__(self, func):
def _call(*args, **kwargs):
func(*args, **kwargs)
return _call
@aa() # nn = aa()(nn)
def nn():
print('rr')