У меня есть такой код:Python вложенная функция прицелы
def write_postcodes(self):
"""Write postcodes database. Write data to file pointer. Data
is ordered. Initially index pages are written, grouping postcodes by
the first three characters, allowing for faster searching."""
status("POSTCODE", "Preparing to sort...", 0, 1)
# This function returns the key of x whilst updating the displayed
# status of the sort.
ctr = 0
def keyfunc(x):
ctr += 1
status("POSTCODE", "Sorting postcodes", ctr, len(self.postcodes))
return x
sort_res = self.postcodes[:]
sort_res.sort(key=keyfunc)
Но СУУ реагирует с NameError:
Traceback (most recent call last):
File "PostcodeWriter.py", line 53, in <module>
w.write_postcodes()
File "PostcodeWriter.py", line 47, in write_postcodes
sort_res.sort(key=keyfunc)
File "PostcodeWriter.py", line 43, in keyfunc
ctr += 1
UnboundLocalError: local variable 'ctr' referenced before assignment
Как я могу это исправить? Я думал, что невесты позволят мне это сделать. Я пробовал использовать «глобальный», но он все еще не работает.
также смотрите на этот вопрос: http://stackoverflow.com/questions/2516652/scoping-problem-in-recursive-closure –