对Python的语句感到困惑

Jes*_*ose 5 python

我在Whoosh文档中看到了一些代码:

with ix.searcher() as searcher:
    query = QueryParser("content", ix.schema).parse(u"ship")
    results = searcher.search(query)
Run Code Online (Sandbox Code Playgroud)

我读到with语句执行__ enter__和__ exit__方法,它们在"with file_pointer:"或"with lock:"形式中非常有用.但没有任何文献能够启发.并且各种示例在"与"形式和传统形式(是其主观的)之间进行翻译时显示出不一致.

请解释

  • 什么是声明
  • 和"as"声明在这里
  • 和两种形式之间的最佳实践
  • 什么类的类借助块来借给他们

结语

http://effbot.org/zone/python-with-statement.htm上的文章有最好的解释.当我滚动到页面底部并看到熟悉的文件操作时,一切都变得清晰了./sf/users/13341821/,希望你回答而不是评论.

Rom*_*huk 9

直接来自PEP-0343的示例:

with EXPR as VAR:
   BLOCK

#translates to:

mgr = (EXPR)
exit = type(mgr).__exit__  # Not calling it yet
value = type(mgr).__enter__(mgr)
exc = True
try:
    try:
        VAR = value  # Only if "as VAR" is present
        BLOCK
    except:
        # The exceptional case is handled here
        exc = False
        if not exit(mgr, *sys.exc_info()):
            raise
        # The exception is swallowed if exit() returns true
finally:
    # The normal and non-local-goto cases are handled here
    if exc:
        exit(mgr, None, None, None)
Run Code Online (Sandbox Code Playgroud)