gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 22:49:15 24 4
gpt4 key购买 nike

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

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com