简体   繁体   English

可以为 Python 中的导入模块定义别名吗?

[英]Can you define aliases for imported modules in Python?

In Python, is it possible to define an alias for an imported module?在 Python 中,是否可以为导入的模块定义别名?

For instance:例如:

import a_ridiculously_long_module_name

...so that is has an alias of 'short_name'. ...所以它有一个别名'short_name'。

import a_ridiculously_long_module_name as short_name

also works for也适用于

import module.submodule.subsubmodule as short_name

Check here在这里检查

import module as name

or或者

from relative_module import identifier as name

If you've done:如果您已经完成:

import long_module_name

you can also give it an alias by:你也可以给它一个别名:

lmn = long_module_name

There's no reason to do it this way in code, but I sometimes find it useful in the interactive interpreter.没有理由在代码中这样做,但我有时发现它在交互式解释器中很有用。

Yes, modules can be imported under an alias name.是的,可以使用别名导入模块。 using as keyword.用作关键字。 See

import math as ilovemaths # here math module is imported under an alias name
print(ilovemaths.sqrt(4))  # Using the sqrt() function

Yes, you can define aliases for imported modules in Python .是的,您可以在 Python 中为导入的模块定义别名

Using pandas is considered a best practice in python because Pandas can import most file formats and link to databases.使用 pandas 被认为是 python 中的最佳实践,因为 Pandas 可以导入大多数文件格式并链接到数据库。

Example: Import pandas library示例:导入 pandas 库

import pandas as pd

Explaining:解释:

pd : is the conventional alias for pandas . pd :是pandas的常规别名。

NP : is the conventional alias for Numpy . NP : 是Numpy的常规别名。

Using short alias helps keep code (concise) and (clean) .使用短别名有助于保持代码(简洁)(干净)

from MODULE import TAGNAME as ALIAS从 MODULE 导入 TAGNAME 作为 ALIAS

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM