简体   繁体   English

Python:“导入模块”与“导入模块为”

[英]Python : 'import module' vs 'import module as'

Is there any differences among the following two statements? 以下两个语句之间是否有区别?

import os
import os as os

If so, which one is more preferred? 如果是这样,哪个更优选?

It is just used for simplification,like say 它只是用于简化,比如说

import random
print random.randint(1,100)

is same as: 与:

import random as r
print r.randint(1,100)

So you can use r instead of random everytime. 因此,您可以每次使用r而不是random

Is there any differences among the following two statements? 以下两个语句之间是否有区别?

No. 没有。

If so, which one is more preferred? 如果是这样,哪个更优选?

The first one ( import os ), because the second one does the exact same thing but is longer and repeats itself for no reason. 第一个( import os ),因为第二个做的完全相同,但是更长,并且无缘无故地重复。

The below syntax will help you in understanding the usage of using "as" keyword while importing modules 以下语法将帮助您了解导入模块时使用“ as”关键字的用法

 import NAMES as RENAME from MODULE searching HOW

Using this helps developer to make use of user specific name for imported modules. 使用此功能可帮助开发人员为导入的模块使用用户特定的名称。 Example: 例:

 import random 
 print random.randint(1,100)

Now I would like to introduce user specific module name for random module thus I can rewrite the above code as 现在,我想为随机模块介绍用户特定的模块名称,以便可以将上面的代码重写为

 import random as myrand
 print myrand.randint(1,100)

Now coming to your question; 现在来问你的问题; Which one is preferred? 首选哪一个? The answer is your choice; 答案是您的选择; There will be no performance impact on using "as" as part of importing modules. 将“ as”用作导入模块的一部分不会对性能产生影响。

If you want to use name f for imported module foo , use 如果要对导入的模块foo使用名称f ,请使用

import foo as f
# other examples
import numpy as np
import pandas as pd

In your case, use import os 在您的情况下,请使用import os

The import .... as syntax was designed to limit errors. import .... as语法旨在限制错误。

This syntax allows us to give a name of our choice to the package or module we are importing—theoretically this could lead to name clashes, but in practice the as syntax is used to avoid them. 这种语法使我们能够为要导入的包或模块提供一个选择名称-理论上这可能会导致名称冲突,但实际上使用as语法来避免这种冲突。

Renaming is particularly useful when experimenting with different implementations of a module. 在尝试模块的不同实现时,重命名特别有用。

Example: if we had two modules ModA and ModB that had the same API we could write import ModA as MyMod in a program, and later on switch to using import MoB as MyMod. 示例:如果我们有两个具有相同API的模块ModA和ModB,则可以在程序中将import ModA编写为MyMod,然后切换到将import MoB用作MyMod。

In answering your question, there is no preferred syntax. 在回答您的问题时,没有首选的语法。 It is all up to you to decide. 由您决定。

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

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