如何在调用另一个函数后强制一个函数退出? [英] How to force a function to exit after calling another function?

查看:70
本文介绍了如何在调用另一个函数后强制一个函数退出?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个函数,每个函数在最后一行调用另一个函数作为传递控制的手段.有没有一种优雅的方法可以强制一个函数在另一个函数执行之前退出,这样您就不会将程序堆积在尸体上?
示例:

I have two functions each calling the other on their final line as a means of passing control. Is there an elegant way to force one function to exit before the other gets executed, so that you don't stack your program up on corpses?
Example:

def f1(x):
    print("f1",x)
    f2(x+1)

def f2(x):
    print("f2",x)
    f1(x+1)

f1(0)

现在的样子,在~1000次调用之后就遇到了递归限制.
当然,一个简单的外部控制结构就可以解决这个问题,但我更愿意把控制流刻在功能.

The way it is now, after ~1000 calls it runs into the recursion limit.
Of cause, a simple external control structure would get rid of the problem, but I'd rather have the control flow engraved in the functions.

但这不是很阻碍吗?

如果 Python 努力成为一种具有高级抽象的高级语言,那么在某个模块上构建模块时,Python 会不会因为不减少其占用空间的行为而崩溃?

If Python strives to be a high-level language with a high level of abstraction, at some point of building modules upon modules, wouldn't Python collapse on its own behavior of not reducing its footprint?

推荐答案

如果您希望一个函数在另一个函数被调用之前退出,您将不得不实际退出该函数而不是让它调用另一个:

If you want one function to exit before the other is called, you will have to actually exit the function instead of having it call the other one:

def f1(x):
    print('f1', x)
    return f2, (x+1,)
def f2(x):
    print('f2', x)
    return f1, (x+1,)

f, args = f1, (0,)
while True:
    f, args = f(*args)

这将需要您想要避免的外部控制结构.

This will require that external control structure you wanted to avoid.

顺便说一句,您尝试使函数调用起作用的方式与 GOTO 非常相似,最终会对程序复杂性和可维护性产生相同的影响.

As an aside, the way you're trying to make function calls work is a lot like GOTO, and can end up having the same effects on program complexity and maintainability.

这篇关于如何在调用另一个函数后强制一个函数退出?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆