[英]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.