在 Python 中遇到“NameError:名稱未定義”錯誤可能會令人沮喪,阻礙程式碼的執行。讓我們調查一下這個錯誤背後的原因並找到有效的解決方案。
當Python遇到對未知變數或類別的引用時,就會出現該錯誤。在提供的代碼中:
s = Something()
s.out()
class Something:
def out():
print("it works")
解釋器在定義 s 變數後嘗試存取 Something 類別。然而,在Python中,類別必須在使用之前定義;否則,解釋器無法識別它們。
要修正這種情況,請在使用 Something 類別之前重新定義它:
class Something:
def out(self):
print("it works")
s = Something()
s.out()
此錯誤的另一個共通點涉及實例方法定義。實例方法需要 self 作為第一個參數,代表實例本身。確保在定義實例方法時包含 self:
class Something:
def out(self):
print("it works")
免責聲明: 提供的所有資源部分來自互聯網,如果有侵犯您的版權或其他權益,請說明詳細緣由並提供版權或權益證明然後發到郵箱:[email protected] 我們會在第一時間內為您處理。
Copyright© 2022 湘ICP备2022001581号-3