【问题标题】:UnboundLocalError: local variable referenced before assignment in Python [duplicate]UnboundLocalError:在Python中赋值之前引用的局部变量[重复]
【发布时间】:2020-05-22 04:42:03
【问题描述】:

所以我在下面的代码中遇到了奇怪的行为。我收到错误,局部变量 flag 在分配之前被引用,但它在顶部分配为全局变量。谁能告诉我这里发生了什么以及为什么flag 没有按预期增加?

import concurrent.futures


flag = 0
def make_some():
    try:
        flag += 1
    except Exception as e:
        print(e)

with concurrent.futures.ThreadPoolExecutor(max_workers=3) as executor:
    tasks = {
        executor.submit(
            make_some
        ): task_id
        for task_id in [1,2,3]
    }
    for future in concurrent.futures.as_completed(tasks):
        pass

【问题讨论】:

    标签: python python-multithreading threadpoolexecutor


    【解决方案1】:

    这应该可以工作(添加global):

    import concurrent.futures
    
    
    flag = 0
    def make_some():
    
        global flag  # <--- USE GLOBAL
    
        try:
            flag += 1
        except Exception as e:
            print(e)
    
    with concurrent.futures.ThreadPoolExecutor(max_workers=3) as executor:
        tasks = {
            executor.submit(
                make_some
            ): task_id
            for task_id in [1,2,3]
        }
        for future in concurrent.futures.as_completed(tasks):
            pass
    

    【讨论】:

    • 能否解释一下为什么需要global
    【解决方案2】:

    你必须使用 global 关键字来解决这个问题

    在此处阅读更多信息https://www.tutorialspoint.com/global-keyword-in-python

    所以没有 global ,每个变量都只在本地范围内,就好像没有定义全局变量一样,因此会出错

    一旦你使用了 global 关键字,那么在内部作用域中,python 会确认存在 global 变量定义

    【讨论】:

    • global 仅用于在内部范围内重新分配全局变量。如果没有局部变量的名称冲突(这就是这里发生的情况),您总是可以从内部范围读取全局变量
    猜你喜欢
    • 2011-05-02
    • 1970-01-01
    • 1970-01-01
    • 2021-12-24
    • 2015-06-14
    • 2018-06-29
    • 1970-01-01
    • 2022-12-28
    • 1970-01-01
    相关资源
    最近更新 更多