Skip to main content
 首页 » 编程设计

python之返回调用此函数的函数

2025年05月04日13itcoder

好的,所以,我正在编写一个带有显示错误消息功能的 Python(v2.7) 代码。但是还有一些其他函数依赖于这个原始的错误检查函数。

现在,当调用这个错误检查函数时,如果有错误,我希望显示一个错误,并调用调用这个错误函数的函数。

例如,如果 function1() 调用了 error() 并且没有错误,则 error() 函数将不执行任何操作重要的。现在,function1() 调用 function2()。当 function2() 调用 error() 函数时,它检测到错误,显示错误消息,然后再次调用 function2()。这就是我想做的,但我不知道如何再次返回调用函数。

请您参考如下方法:

隐式调用调用函数必然会导致无限循环、错误(除非您绝对确保所有调用错误的方法都是幂等的,即使过早中止)、困惑,而且无论如何都是完全非 Python 的。您正在寻找的只是常规错误处理:

def f2(): 
   try: 
       1/0 # complicated code, potentially raising an error 
   except ZeroDivisionError: # Or BaseException, if you gotta catch them all 
       error() 
       # clean up, restore a consistent state 
   # go on, no matter whether the error occurred or did not 

如果简单地重试有帮助,您只需将其写出来:

 def sometimes_fails(): 
     1 / random.randint(0,1) 
 
 def f(): 
    while True: 
        try: 
            sometimes_fails() 
         except ZeroDivisionError: 
            continue # try again 
         break # abort 

对于非常不寻常、极其复杂(幂等)且因此容易出错的行为,使用像 error 这样的通用名称不是一个好主意。

这个答案是由On Error Resume Next给你的.