如何处理不存在的变量“赋值前引用”

2024-10-02 20:29:51 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一些代码,在满足某个条件时创建一个变量:

if self.left: 
    left_count = self.left.isUnivalTree()

下面几行我有代码:

if left_count and right_count: 
    total_count = right_count + left_count

这将引发以下错误:

local variable 'left_count' referenced before assignment

我该怎么办?当然,通过说if left_count...我可以解释这个事实

(这个错误是通过为函数中的所有参数设置一个默认值来修复的,但是我只是想知道是否有更简单的方法来解决这个问题,因为我需要为5个参数设置一个默认值?)


Tags: and代码selfrightiflocalcount错误
3条回答

如果self.left不是True,则不进行赋值,请尝试以下设置None默认值的方法:

left_count = self.left.isUnivalTree() if self.left else None

根据您的问题更新,在函数上设置默认参数更好,这正是它们的用途

如果isUnivalTree返回bool(由于名称的原因,应该返回bool):

left_count = self.left and self.left.isUnivalTree()

否则:

left_count = self.left.isUnivalTree() if self.left else None

而不是:

left_count = False
if self.left: left_count = self.left.isUnivalTree()

只需使用and的短路行为:

left_count = self.left and self.left.isUnivalTree()

相关问题 更多 >