簡體   English   中英

Python全局變量給出了NameError

[英]Python Global variable gives NameError

我的代碼:

def draw_lines(img, lines, color, thickness) :
    x_right = []
    y_right = []
    x_left = []
    y_left = []
    numItr = 1

    for line in lines :
        for x1,y1,x2,y2 in lines :
        global numItr
        numItr += 1

這是錯誤:

NameError: name 'numItr' is not defined    

無需在此處使用global或非nonlocal ,只需:

def draw_lines(img, lines, color, thickness) :
    x_right = []
    y_right = []
    x_left = []
    y_left = []
    numItr = 1

    for line in lines :
        for x1,y1,x2,y2 in lines :
            numItr += 1

如果要寫入模塊級變量,則只需要global 如果你想寫入一個局部於詞法封閉函數的變量,你只需要nonlocal變量,例如你定義函數的函數。

這兩種情況都不適用於您的代碼,您只是停留在一個函數中。

在您的情況下,解釋器會抱怨,而通過使用global一詞,您表示有一個名為numItr的模塊級變量,但實際上並沒有。

也許您的問題是numItr未在draw_lines函數之前draw_lines 看看這個https://stackoverflow.com/a/423596/6876911

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM