Python世界:报错Debug之referenced before assignment

Python世界:报错Debug之referenced before assignment

一句话总结

类中函数引用结构体变量,出现报错如下:

Python Debug:local variable 'split_num' referenced before assignment

解决:该变量改为全局变量使用,并在用前声明 global split_num

案例分析

使用背景:在函数内部定义变量,再接着定义子函数,引用了该变量。

如下面代码就会报错:local variable 'depth' referenced before assignment

python 复制代码
def f1():
depth = 0
    def func():
         depth += 1
    func()
return

根因分析:

  • 本质是函数内部声明的变量,默认类型是局部变量。
  • 而跟全局变量同名时,先引用局部变量,会不符合预期,提示未被初始化。

全局变量报错:UnboundLocalError: local variable 'l' referenced before assignment

相关推荐
花酒锄作田3 小时前
Pydantic校验配置文件
python
hboot3 小时前
AI工程师第四课 - 深度学习入门
pytorch·python·神经网络
ZhengEnCi14 小时前
P2M-Matplotlib折线图完全指南-从数据可视化到趋势分析的Python绘图利器
python·matlab·数据可视化
ZhengEnCi15 小时前
P2L-Matplotlib饼图完全指南-从数据可视化到图表定制的Python绘图利器
python·matlab
曲幽15 小时前
你的REST接口还在“过度投喂”数据吗?——FastAPI + GraphQL实战避坑指南
python·fastapi·web·graphql·route·cors·rest·strawberry
用户83580861879116 小时前
基于 Self-RAG 与列表级重排序的进阶 RAG 系统设计与实现
python
Warson_L1 天前
Python `Annotated` 与 LangGraph Reducer 学习笔记
python
韩师傅1 天前
海天线算法的前世今生
python·计算机视觉
韩师傅1 天前
当你的甲方设备过烂,要如何快速出效果?
python·计算机视觉
Warson_L1 天前
LangGraph的MessageState and HumanMessage
python