![](/img/trans.png)
[英]How to catch the lookup of non-existent nested variables on a Python class?
[英]How to deal with non-existent variables “reference before assignment”
如果滿足特定條件,我有一些代碼可以創建變量:
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個參數設置默認值?)
如果self.left
不是True
,則沒有分配,請嘗試以下設置默認值None
:
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()
如果isUnivalTree
返回布爾值(由於名稱的原因,它應該是):
left_count = self.left and self.left.isUnivalTree()
除此以外:
left_count = self.left.isUnivalTree() if self.left else None
或捕獲NameError
try:
if left_count and right_count: total_count = right_count + left_count
except NameError:
print('NameError catched')
total_count = 0
或檢查是否已定義:
if 'left_count' in locals():
print('left_count is defined')
這一切都取決於最適合您的工作流程
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.