Sam*_*Sam 3 python loops function python-3.x
我有一个正在一遍又一遍地运行的函数。在该函数内部,我希望仅在该函数第一次运行时运行特定的段。
我不能使用函数外部的任何变量,例如
firstTime = True
myFunction(firstTime): #function is inside a loop
if firstTime == True:
#code I want to run only once
firstTime = False
#code I want to be run over and over again
Run Code Online (Sandbox Code Playgroud)
我也不想使用全局变量。
有什么想法如何实现这一点?
使用可变的默认参数:
>>> def Foo(firstTime = []):
if firstTime == []:
print('HEY!')
firstTime.append('Not Empty')
else:
print('NICE TRY!')
>>> Foo()
HEY!
>>> Foo()
NICE TRY!
>>> Foo()
NICE TRY!
Run Code Online (Sandbox Code Playgroud)
为什么这有效?查看此问题以了解更多详细信息。