【python】错误:UnboundLocalError: local variable ‘XXX‘ referenced before assignment

topNSuccessor=None
def reverseTopN(self, head: ListNode, right: int) -> ListNode:
	if right==1:
		topNSuccessor=head.next
        return head

执行此代码报错:UnboundLocalError: local variable ‘XXX’ referenced before assignment

错误: UnboundLocalError:在赋值之前引用了局部变量“XXX”

原因: 在函数内部对变量赋值进行修改后,该变量就会被Python解释器认为是局部变量而非全局变量,当程序执行到topNSuccessor=head.next的时候,此操作是给topNSuccessor赋值,topNSuccessor则被认为是局部变量,而解释器在函数内部找不到topNSuccessor的定义,自然报错
解决方式: 在函数内部,给变量添加global修饰符,声明此变量为全局变量

topNSuccessor=None
def reverseTopN(self, head: ListNode, right: int) -> ListNode:
	global topNSuccessor #全局变量
	if right==1:
		topNSuccessor=head.next
        return head
上一篇:PaddleSeg UnboundLocalError: local variable ‘images‘ referenced before assignment


下一篇:dyld: Library not loaded: /usr/local/opt/icu4c/lib/libicui18n.64.dylib Referenced from