lazy_object_proxy
懒惰对象代理模块:lazy_object_proxy
探索该模块:这个模块有何用?
>>> import lazy_object_proxy >>> def expensive_func(): ... a = 2 ... b = 2 ... print("开始计算") ... return a*b ... >>> expensive_func() 开始计算 4 >>> obj <Proxy at 0x0000029E6A262A48 with factory <function expensive_func at 0x0000029E6A0FD708>> >>> print(obj) 开始计算 4 >>> obj <Proxy at 0x0000029E6A262A48 wrapping 4 at 0x00007FFD772F7160 with factory <function expensive_func at 0x0000029E6A0FD708>> >>> print(obj) 4
分析上面的代码:懒惰对象代理模块处理过后的函数对象,第一次调用时会全部执行里面的输出语句,而第二次不会调用但是会输出函数的返回值。
#-*-coding:GBK-*- import lazy_object_proxy #导入懒性对象代理模块 from time import sleep def expensive_func(): print("Starting calculation") #Just as example for a very slow computation sleep(2) print("Finished calculation") #return the result of the calculation return 10 obj = lazy_object_proxy.Proxy(expensive_func) #Function is called only when object is actually used (仅当实际使用对象时才调用函数) print(obj) #Now expensive_func is called (expensive_func函数被调用) print(obj) #The result without calling the expensive_func (这里的结果没有调用expensive_func函数)