有没有可能调用一个函数,处理它的一些条件,中断,再次调用它,然后让它从停止的地方重新开始呢?

2024-09-27 07:30:55 发布

您现在位置:Python中文网/ 问答频道 /正文

如果我有:

def foo(x):

    if x == y:
        blah
    elif x == z:
        blah1
    if x == y:
        blah2
    elif x == a:
        blah3
    if x == y:
        blah
    elif x == y:
        blah4
    if x == b:
        blah5
    elif x == c:
        blah6

我能不能在第三个条件结束时中断,做一些其他的处理,然后让这个函数在我再次调用它时从它停止的地方开始呢?你知道吗


Tags: 函数iffoodef地方条件blahelif
1条回答
网友
1楼 · 发布于 2024-09-27 07:30:55

就像伍布尔说的,你可以用发电机来做这个,至少如果我知道你想要什么的话。我在野外见过几次,但很少见到。你知道吗

def foo(x):
    if x == 6:
        print 'six'
    elif x == 3:
        print 'three'
    yield
    if x > 4:
        print 'greater than four'
    else:
        print 'not greater than four'
    yield

能产生

>>> f = foo(6)
>>> f
<generator object foo at 0x1004b25a0>
>>> next(f)
six
>>> next(f)
greater than four
>>> next(f)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
StopIteration

不过,也许有更好的方法来做你想做的事。你知道吗

相关问题 更多 >

    热门问题