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

我也不想使用全局变量。

有什么想法可以做到这一点吗?

使用可变的默认参数:

>>> def Foo(firstTime = []):
    if firstTime == []:
        print('HEY!')
        firstTime.append('Not Empty')
    else:
        print('NICE TRY!')

>>> Foo()
HEY!
>>> Foo()
NICE TRY!
>>> Foo()
NICE TRY!

为什么这样做?查看此问题了解更多详细信息。

您可以使用实现__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 

我可以为此在地狱里度过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():检查变量的存在性,但我更喜欢这种方式。

这是对我以前的代码的改进。但有件事告诉我可以用var()['VerySpecificVariableName']做点什么。IDK,这个不会通过隐藏异常

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'

最新更新