Python中有标签/goto吗?

2024-05-29 04:37:58 发布

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

Python中是否有可以跳转到特定代码行的goto或任何等效代码?


Tags: 代码goto
3条回答

不,Python不支持labels和goto,如果这正是您所追求的。它是一种(高度)结构化的编程语言。

我最近wrote a function decorator启用了Python中的goto,就像这样:

from goto import with_goto

@with_goto
def range(start, stop):
    i = start
    result = []

    label .begin
    if i == stop:
        goto .end

    result.append(i)
    i += 1
    goto .begin

    label .end
    return result

我不知道为什么会有人想做那样的事。也就是说,我不是很认真。但我想指出,这种元编程实际上在Python中是可能的,至少在CPython和PyPy中是可能的,而不仅仅是像other guy那样滥用调试器API。但是你必须处理字节码。

Python提供了使用一级函数执行goto的一些功能。例如:

void somefunc(int a)
{
    if (a == 1)
        goto label1;
    if (a == 2)
        goto label2;

    label1:
        ...
    label2:
        ...
}

可以在python中这样做:

def func1():
    ...

def func2():
    ...

funcmap = {1 : func1, 2 : func2}

def somefunc(a):
    funcmap[a]()  #Ugly!  But it works.

当然,这不是替代goto的最佳方法。但是,如果不知道你想用goto做什么,就很难给出具体的建议。

@ascobol

最好的办法是将其括在函数中或使用异常。对于函数:

def loopfunc():
    while 1:
        while 1:
            if condition:
                return

例外情况:

try:
    while 1:
        while 1:
            raise BreakoutException #Not a real exception, invent your own
except BreakoutException:
    pass

如果你来自另一种编程语言,使用异常来做这样的事情可能会有点尴尬。但我认为,如果您不喜欢使用异常,那么Python不是您的语言。:-)

相关问题 更多 >

    热门问题