Python:在无限循环函数中只运行一次代码段。。?

Python:在无限循环函数中只运行一次代码段。。?,python,function,loops,python-3.x,Python,Function,Loops,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

我有一个函数正在被反复运行。在该函数中,我希望只在第一次运行该函数时运行特定的段

我不能使用函数之外的任何变量,例如

    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!

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

您可以使用一个实现
\u调用\u
魔术方法的
类。
这样做的好处是可以使用多个实例或重置实例

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语句中的代码一次。
... 现在当然可以用
检查变量是否存在,如果locals()中的'myVar':
,但我更喜欢这种方式。

这是我以前代码的改进。不过,有些事情告诉我,我可以用var()['verysspecificvariablename']做点什么。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'

可能重复您是否尝试仅在函数内部使用全局变量?它符合你的要求吗?@LaurentH。想了想,但我尽量避免任何外部参考:什么样的循环?它是否碰巧有一个可以传递的索引?想象一下,有人正在阅读该代码并试图理解它应该做什么。。。所以,是的,100年的地狱生活可能是一个很好的回应。