You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

函数内定义frame_dict,forFrame中声明global仍提示未定义求助

解决嵌套函数无法访问外层函数局部变量的问题

错误原因

你在forFrame里用global frame_dict是错误的——frame_dict不是全局作用域的变量,它是外层函数yolo_neural_network的局部变量。global关键字只能引用模块级的全局变量,无法引用外层函数的局部变量,所以这个声明无效,导致函数找不到frame_dict。

解决方案

方案1:使用nonlocal关键字(推荐,Python3+支持)

把global替换为nonlocal,它专门用来引用外层函数的局部变量:

def forFrame(frame_number, output_array, output_count):
    nonlocal frame_dict
    frame_dict[tv_c].append(output_count)

方案2:用functools.partial绑定参数(更安全,避免闭包陷阱)

这种方法可以明确传递需要的变量,避免闭包变量的延迟绑定问题:

  1. 先导入functools模块
  2. 修改forFrame函数,把frame_dict和tv_c作为参数传入
  3. 用partial预先绑定这两个参数,再传给per_frame_function

修改后的代码片段:

from functools import partial

# ... 其他代码 ...

def forFrame(frame_dict, tv_c, frame_number, output_array, output_count):
    frame_dict[tv_c].append(output_count)

vid_obj_detect.detectObjectsFromVideo(
    input_file_path=input_file_path,
    output_file_path=output_file_path,
    log_progress=True,
    frame_detection_interval=60,
    minimum_percentage_probability=70,
    per_frame_function=partial(forFrame, frame_dict, tv_c),
    save_detected_video=True
)

方案3:将frame_dict改为全局变量(不推荐)

把frame_dict的定义移到yolo_neural_network函数外面,作为模块级全局变量,然后在函数内用global声明。但这种方法会污染全局作用域,多次调用函数时容易出现数据冲突,不建议使用。

内容的提问来源于stack exchange,提问作者Jaime Ken Pereira

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.31 18:01:19