[英]python interactive mode module import issue
我相信我有一个所谓的范围问题,也许是名称空间。 不太确定我是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
在交互模式下,我确实导入了re并且可以使用re函数,但是由于某些原因,当我试图执行模块时,它不起作用。
我需要将re导入到课程范围内吗? 我不这么认为,因为如果在当前作用域中找不到python,它将不会搜索其他作用域?
感谢您的帮助,如果有更好的搜索方法,我将非常有兴趣。 谢谢
将“ import re”从底部“ if ...”移到文件顶部:
import re
class ....
您仅在作为程序运行时导入re模块,而不作为模块导入。
(此外,Python样式更喜欢使用大写的类名。)
Python不会“提前”运行任何东西; 当遇到它时它将运行代码。 “提前”完成的唯一事情就是将源代码转换为字节码。
导入模块时, __name__
是模块的名称,而不是__main__
。 因此,最后的if
块中的代码不会执行,并且不会导入re
。 然后,当您尝试使用该类时,会在需要(访问re.compile
)且找不到(因为该模块先前未导入)时立即查找名称re
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.