python - 从模块导入多个类的语法

标签 python

我正在阅读一些包含以下导入语句的代码:

from threading import local as thread_local, Event, Thread

起初这个语法让我很困惑,但我认为它相当于:

from threading import local as thread_local
from threading import Event
from threading import Thread

谁能证实情况是否如此?

最佳答案

您可以在官方文档中查看这一点。这是documentation for the import syntax :

import_stmt     ::=  "import" module ["as" name] ( "," module ["as" name] )*
                     | "from" relative_module "import" identifier ["as" name]
                     ( "," identifier ["as" name] )*
                     | "from" relative_module "import" "(" identifier ["as" name]
                     ( "," identifier ["as" name] )* [","] ")"
                     | "from" module "import" "*"
module          ::=  (identifier ".")* identifier
relative_module ::=  "."* module | "."+
name            ::=  identifier

请注意如何始终拥有导入模块[“as”名称]标识符[“as”名称],包括在列表定义中:

( "," identifier ["as" name] )* 

这意味着逗号 , 后跟一个标识符,可以选择使用 as 指定名称,并且 )* 表示“该组可以重复零次或多次,其中包括您提供的示例。

稍后也会在同一页面上对此进行解释:

The from form uses a slightly more complex process:

  1. find the module specified in the from clause, loading and initializing it if necessary;
  2. for each of the identifiers specified in the import clauses:
    1. check if the imported module has an attribute by that name
    2. if not, attempt to import a submodule with that name and then check the imported module again for that attribute
    3. if the attribute is not found, ImportError is raised.
    4. otherwise, a reference to that value is stored in the local namespace, using the name in the as clause if it is present, otherwise using the attribute name

关于python - 从模块导入多个类的语法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39850390/

相关文章:

python - 在 Python 中将 OpenCV SURF 特征转换为 float32 数组

python - 如何克服 "datetime.datetime not JSON serializable"?

python - 我自己的 Python OCR 程序

python - 提取数据帧列匹配的行索引

python - Emacs Python.el,语法高亮怪癖

python - 使用不同数量的核心进行多处理时,将结果保存到磁盘会导致不同大小的对象