[英]UnBoundLocalError: local variable referenced before assignment (Python)
[英]Python - UnboundLocalError: local variable “ID” referenced before assignment
Id, conf = recognizer.predict(gray[y:y+h,x:x+w]
def hour(cn):
for z in range(9,17):
if now.hour == z:
worksheet(cn, str(z)+":00")
def identify(number):
sht = gc.open("Test")
wks3 = sht.worksheet("NAMES")
b = wks3.acell('B'+str(number)).value
a = wks3.acell('A'+str(number)).value
if(Id == a and conf<65):
print(Id, conf)
Id = str(b)
Time = time.ctime()
hour(number)
elif(conf>64):
print(conf)
Id = "Unknown"
for m in range(2,100):
identify(m)
上面的代碼被用於人臉識別,我復制了我認為必要的內容, 而不是整個代碼。
我正在嘗試創建一個要在for循環中回調的函數
我究竟做錯了什么? 我已經看了6個小時了,而我嘗試的一切似乎都不起作用。
我收到一條消息,說“ UnboundLocalError:分配前已引用本地變量'Id'”
這是不可能的,因為我要分配:
a = wks3.acell('A'+str(number)).value
因此,它會從Google電子表格中獲取ID號,並檢查該ID號是否等於該ID號,有人可以告訴我我在哪里出問題了嗎?
def identify(number):
sht = gc.open("Test")
wks3 = sht.worksheet("NAMES")
b = wks3.acell('B'+str(number)).value
a = wks3.acell('A'+str(number)).value
#because you did, Id = ?
if(Id == a and conf<65):
print(Id, conf)
Id = str(b)
Time = time.ctime()
hour(number)
elif(conf>64):
print(conf)
Id = "Unknown"
因為這樣做了,所以變量ID不會作為任何參數或全局/局部變量或作為現有類的參數傳遞。
如果Id是參數:
def identify(number,Id):
如果Id是全局變量:
def identify(number):
global Id
如果Id是局部變量:
def identify(number):
id = None # or some other data type
如果Id是某個類的論點:
some_class.Id
簡而言之,您在初始化之前引用了ID。 這是菜鳥的錯誤,有一些東西可以讓您在ifif else語句中實際初始化一個變量,但是您不需要拋出上述規則的任何邏輯。
if True: Id = 2; elif False: Id = 3; else: Id =0 #this is pseudocode, don't paste it in.
還請記住,下一個變量也是Unbound conf
編輯:
通常為了避免這個問題,我們編寫如下代碼:
def somefunction(parm1,parm2... ):
# global variables : description for variable stack is optional
global var1,var2 # if needed
#local variables
var3,var4 = None;
var5 = 'something else'
#in body functions : functions inside functions or just general program functions
def a(... ): return ...
#body : actually what function/program does.
# returning , finishing statement.
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.