Python:在无限循环函数中仅运行代码段一次?
我有一个函数,它会被反复调用。在这个函数里面,我希望有一个特定的部分只在第一次运行这个函数的时候执行。
我不能使用函数外的任何变量,比如:
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
而且我也不想使用全局变量。
有没有什么办法可以做到这一点呢?
相关文章:
- 暂无相关问题
4 个回答
0
这是我之前代码的改进版本。我感觉我可以对 var()['VerySpecificVariableName'] 做点什么。不过,我不知道,这个代码不会隐藏异常。
try:
if VerySpecificVariableName=='123':
print("You did it already.")
except NameError as e:
if not ('VerySpecificVariableName' in repr(e)):
raise
print ('your code here')
VerySpecificVariableName='123'
1
我可能会因为这个在地狱待上100年:
#Actually may I not get 100 years in hell for this; my method has the advantage that you can run every single part of it with no hitch whereas, all the other code requires you to run some other part 'only once'.
try:
if abc=='123':
print("already done")
except:
#Your code goes here.
abc='123'
这段代码应该只会执行一次,位于try语句中的代码。...当然,你可以用if 'myVar' in locals():
来检查变量是否存在,但我觉得这样做更好。
1
你可以使用一个包含 __call__
魔法方法的 class
(类)。这样做的好处是,你可以使用多个实例,或者重置这个实例。
class MyFunction():
def __init__(self):
self.already_called = False
def __call__(self):
if not self.already_called:
print('init part')
self.already_called = True
print('main part')
func = MyFunc()
func()
func()
这样会得到:
init part
main part
main part
5
使用可变的默认参数:
>>> def Foo(firstTime = []):
if firstTime == []:
print('HEY!')
firstTime.append('Not Empty')
else:
print('NICE TRY!')
>>> Foo()
HEY!
>>> Foo()
NICE TRY!
>>> Foo()
NICE TRY!
为什么这样可以呢?想了解更多细节,可以查看这个问题。