【发布时间】:2011-05-31 05:59:50
【问题描述】:
我相信我有所谓的范围问题,也许是名称空间。不太确定我是 python 新手。
我正在尝试制作一个使用正则表达式搜索列表的模块。我确信有更好的方法可以做到这一点,但是我遇到的这个错误困扰着我,我想了解原因。
这是我的代码:
class relist(list):
def __init__(self, l):
list.__init__(self, l)
def __getitem__(self, rexp):
r = re.compile(rexp)
res = filter(r.match, self)
return res
if __name__ == '__main__':
import re
listl = [x+y for x in 'test string' for y in 'another string for testing']
print(listl)
test = relist(listl)
print('----------------------------------')
print(test['[s.]'])
当我通过命令行运行这段代码时,它会按照我期望的方式运行;但是,当我通过 python 交互模式运行它时,我得到了错误
>>> test['[s.]']
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "relist.py", line 8, in __getitem__
r = re.compile(rexp)
NameError: global name 're' is not defined
在交互模式下,我确实 import re 并且可以使用 re 函数,但由于某种原因,当我尝试执行模块时它不起作用。
我需要将 re 导入类的范围吗?我不这么认为,因为如果在当前范围内没有找到,python 不会搜索其他范围吗?
感谢您的帮助,如果有更好的搜索方式,我很想知道。谢谢
【问题讨论】:
标签: python namespaces scope