这对你有帮助吗?
它利用了默认参数定义的特性以及列表不是变量而是引用集合这一事实,在我的代码中只有一个(简短地说)
from time import sleep,time
stringToWrite = [None]
pauseSeconds = [0]
def writeAndPause(stw = stringToWrite, pz = pauseSeconds, keep = [time()]):
if stw[0]:
print stw[0]
else:
print 'START'
print ' having waited ',time()-keep[0],'seconds, must wait',pz[0],'seconds'
keep[0] = time()
sleep(pz[0])
writeAndPause()
for a,b in (('first',1),('second',2.05),('third',3.4),('fourth',0.88),
('BANANA',0.2),('APPLE',1.5),
('PEAR',0.77),('CHERRY',4),
('ORANGE',0.1),('NUT',6),
('APRICOT',0.56),('PLUM',2.5)):
stringToWrite[0] = a
pauseSeconds[0] = b
writeAndPause()
结果
START
having waited 0.0310001373291 seconds, must wait 0 seconds
first
having waited 0.0320000648499 seconds, must wait 1 seconds
second
having waited 1.01600003242 seconds, must wait 2.05 seconds
third
having waited 2.15600013733 seconds, must wait 3.4 seconds
fourth
having waited 3.42100000381 seconds, must wait 0.88 seconds
BANANA
having waited 0.905999898911 seconds, must wait 0.2 seconds
APPLE
having waited 0.266000032425 seconds, must wait 1.5 seconds
PEAR
having waited 1.51499986649 seconds, must wait 0.77 seconds
CHERRY
having waited 0.796999931335 seconds, must wait 4 seconds
ORANGE
having waited 4.03200006485 seconds, must wait 0.1 seconds
NUT
having waited 0.140000104904 seconds, must wait 6 seconds
APRICOT
having waited 6.03099989891 seconds, must wait 0.56 seconds
PLUM
having waited 0.765000104904 seconds, must wait 2.5 seconds