python - Python 中出现意外的 "except"

标签 python python-2.7 wrapper

请帮助 python 脚本。 python 2.7。 我试图制作一些功能来通过错误检查重复操作。 所以在我认为下面调用的函数中(lib_func),没有错误。 但是 repeater() 中的“except”以任何方式提升。

如果我不在 lib_func() 中使用“x”——它可以正常工作,但我仍然需要在 lib_func() 中添加参数。

抱歉英语不好,在此先感谢您的帮助。

def error_handler():
    print ('error!!!!!!')

def lib_func(x):
    print ('lib_func here! and x = ' + str(x))

def repeater(some_function):
    for attempts in range(0, 2):
        try:
            some_function()
        except:
            if attempts == 1:
                error_handler()
            else:
                continue
    break
return some_function

repeater(lib_func(10))

输出:

lib_func here! and x = 10
error!!!!!!

Process finished with exit code 0

最佳答案

你的缩进是错误的,转发器应该按如下方式调用:

def repeater(some_function):
    for attempts in range(0, 2):
        try:
            some_function()
        except:
            if attempts == 1:
                error_handler()
            else:
                continue
    return some_function()

repeater(lambda: lib_func(10)) # pass `lib_func(10)` using lambda

我不明白你想要实现什么,但是上面的代码在 for 循环中执行了几次 lib_func(10)

或者,您可以使用部分:

from functools import partial    
lf = partial(lib_func, 10)    
repeater(lf)

关于python - Python 中出现意外的 "except",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29249152/

相关文章:

python - 预先确定放大叶片的最佳水平

python - Authorization header 值中的 Token 关键字是否有任何解释?

python - 一次对多个字符串项使用 .append

python - 将列表拆分为更小的列表

python - 什么是引用窃取和借用?

php - 包装类和依赖注入(inject)

Python - 将 Tkinter 图形添加到 PyQt 小部件

python - Python 中等效的 'nth_element' 函数是什么?

c++ - 包装函数只能看到它自己?

html - 使包装器/容器响应?