【问题标题】:python interactive mode module import issuepython交互模式模块导入问题
【发布时间】: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


    【解决方案1】:

    将“import re”从底部的“if...”移到文件的顶部:

    import re
    
    class ....
    

    您只是在作为程序运行时导入 re 模块,而不是作为模块导入。

    (另外,Python 风格更喜欢大写的类名。)

    【讨论】:

      【解决方案2】:

      Python 不会“提前”运行任何东西;它在遇到它时运行代码。唯一“提前”完成的事情就是将源代码翻译成字节码。

      当您导入模块时,__name__ 是模块的名称,而不是 __main__。因此,最后if 块中的代码不会被执行,re 也不会被导入。然后,当您尝试使用该类时,名称 re 会在需要时立即查找(访问 re.compile),但未找到(因为之前未导入该模块)。

      【讨论】:

        猜你喜欢
        • 2016-04-05
        • 1970-01-01
        • 2020-08-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-12-19
        • 2018-09-20
        相关资源
        最近更新 更多