Python中有标签/ goto吗?gotoPython中是否有一个或任何等价物能够跳转到特定的代码行?
3 回答

BIG阳
TA贡献1859条经验 获得超6个赞
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 ownexcept BreakoutException: pass
如果你来自另一种编程语言,使用异常来做这样的事情可能会有点尴尬。但我认为,如果您不喜欢使用异常,Python就不适合您。:-)

皈依舞
TA贡献1851条经验 获得超3个赞
我最近写了一个函数装饰器,goto
在Python 中启用,就像这样:
from goto import with_goto@with_gotodef 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中是这样,而且不仅像其他人那样滥用调试器API 。你必须弄乱字节码。
添加回答
举报
0/150
提交
取消