将函数绑定到只在所需范围内运行一次。
shibari的Python项目详细描述
将函数绑定到只在所需范围内运行一次。
文档
rig类公开了两个方法:bind和free。bind接受一个参数:用于绑定函数的作用域的名称。
用bind包装的函数将只调用一次,直到它所在的作用域被释放为止。
在函数执行之后,用free包装的函数将释放特定范围内的所有绑定函数。
示例:
importshibaririg=shibari.Rig('ebi')@rig.bind('ebi')deftimestamp():returnstr(time.time())@rig.free('ebi')deffinish():pass>>>t=timestamp()>>>t2=timestamp()>>>assertt==t2>>>finish()>>>t3=timestamp()>>>t4==timestamp()>>>assertt!=t3>>>assertt3==t4
接受参数的函数可以被绑定,但在释放它们之前总是返回相同的结果。
示例:
importshibaririg=shibari.Rig('ebi')@rig.bind('ebi')deftimestamp(a,b):returnf'{a}_{str(time.time())}_{b}'>>>t=timestamp('goodbye','world')>>>t2=timestamp('hello','space')>>>assertt==t2