python 作用域嵌套_Python嵌套函数作用域

I have code like this:

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)

But ctr responds with a NameError:

Traceback (most recent call last):

File "PostcodeWriter.py", line 53, in

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

How can I fix this? I thought nester scopes would have allowed me to do this. I've tried with 'global', but it still doesn't work.

解决方案

Since the nested function can't rebind a nonlocal name (in Python 2; in Python 3, you'd use the nonlocal statement to enable that), you need to perform your incrementing without barename rebinding (by keeping the counter as an item or attribute of some barename, not as a barename itself). For example:

...

ctr = [0]

def keyfunc(x):

ctr[0] += 1

status("POSTCODE", "Sorting postcodes", ctr, len(self.postcodes))

return x

...

and of course use ctr[0] wherever you're using bare ctr now elsewhere.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值