我正在阅读一些包含以下导入语句的代码:
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:
- find the module specified in the
from
clause, loading and initializing it if necessary;- for each of the identifiers specified in the import clauses:
- check if the imported module has an attribute by that name
- if not, attempt to import a submodule with that name and then check the imported module again for that attribute
- if the attribute is not found,
ImportError
is raised.- 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/