如何从模块中导入多个项目并在 Python 中重命名它们?
How can I import multiple items from a module and rename them in Python?
我想从 math
导入 atan
和 degree
并重命名它们。
我试过用这个:
from math import atan,degree as t,z
但这给出了 ImportError: cannot import name 'z'
.
我对 "import multiple modules and rename" 进行了多次 Google 搜索,但都没有结果。 Python 手册没有帮助 - 导入页面没有解释这一点(据我所知)。
如何从一个模块导入多个项目,并重命名它们?
您必须为每个项目使用 as
:
from math import atan as t, degree as z
这将全部导入并重命名。
Python Reference Manual 实际上涵盖了这一点。它在 import
语句的描述中说:
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" "*"
现在,这个符号乍一看有点令人困惑,但是随着时间的推移使用编程语言,你会变得更加熟悉。它通常被称为 "BNF"(代表 Backus-Naur Form)。大多数编程语言参考资料都会使用它的某个版本。
从上面的示例中,我们看到以下符号可以做一些解释:
- 竖线或管道字符 (
|
) -- 这用于分隔替代项
- 星号/星号 (
*
) -- 这意味着前面的(通常是封闭的语句)重复零次或多次
- 方括号(
[
和]
)--这些表示出现的封闭部分是可选的,因此包含零次或一次。
- 圆括号(
(
和 )
)-- 这些用于对语句进行分组以使星号在 上生效
将上面的引用缩减为您似乎感兴趣的内容,我们有:
"from" relative_module "import" identifier ["as" name]
( "," identifier ["as" name] )*
TL;DR 对于您给出的示例,导致法律声明为
from math import atan as t, degree as z
我想从 math
导入 atan
和 degree
并重命名它们。
我试过用这个:
from math import atan,degree as t,z
但这给出了 ImportError: cannot import name 'z'
.
我对 "import multiple modules and rename" 进行了多次 Google 搜索,但都没有结果。 Python 手册没有帮助 - 导入页面没有解释这一点(据我所知)。
如何从一个模块导入多个项目,并重命名它们?
您必须为每个项目使用 as
:
from math import atan as t, degree as z
这将全部导入并重命名。
Python Reference Manual 实际上涵盖了这一点。它在 import
语句的描述中说:
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" "*"
现在,这个符号乍一看有点令人困惑,但是随着时间的推移使用编程语言,你会变得更加熟悉。它通常被称为 "BNF"(代表 Backus-Naur Form)。大多数编程语言参考资料都会使用它的某个版本。
从上面的示例中,我们看到以下符号可以做一些解释:
- 竖线或管道字符 (
|
) -- 这用于分隔替代项 - 星号/星号 (
*
) -- 这意味着前面的(通常是封闭的语句)重复零次或多次 - 方括号(
[
和]
)--这些表示出现的封闭部分是可选的,因此包含零次或一次。 - 圆括号(
(
和)
)-- 这些用于对语句进行分组以使星号在 上生效
将上面的引用缩减为您似乎感兴趣的内容,我们有:
"from" relative_module "import" identifier ["as" name]
( "," identifier ["as" name] )*
TL;DR 对于您给出的示例,导致法律声明为
from math import atan as t, degree as z