如何理解.导入python吗? [英] How to understand from . import in python?

查看:19
本文介绍了如何理解.导入python吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是python和flask框架的新手.

I am new to python and flask framework.

以下代码:

from flask import Blueprint
main = Blueprint('main', __name__)
from . import views, errors

我发现python有很多导入方式,例如:

I found python has many import ways, for example:

import foo
import foo.bar
from foo import bar
from foo import bar, baz
from foo import *
from foo import bar as fizz

但是如何从中理解.导入... ?

推荐答案

当您使用 import XXX 时,您将导入XXX名称空间下的XXX的所有内容,并且可以使用XXX来访问它们.abc,XXX.example等...

When you use import XXX, you import all the contents of XXX under the namespace XXX, and you have access to them using XXX.abc, XXX.example etc...

当您使用XXX import abc 中的时,仅覆盖了 globals()字典的变量abc.特殊的 from XXX import * 会执行相同的操作,但对于名称不是以下划线开头的所有变量.

When you use from XXX import abc, you only overwrite the variable abc of your globals() dictionnary. The special from XXX import * does the same, but for all variables whose name doesn't begins with an underscore.

最后,"as"关键字使您可以为导入的模块/函数/变量指定所需的名称.

Finally, the "as" keyword allows you to give to the imported module/function/variable the name you want.

当您的模块包含一些文件夹并且要从另一个文件导入时,.指向包含当前文件的目录,..指向包含当前文件的目录,依此类推.

When you have a module containing some folders, and you want to import from another file, . refers to the directory containing the current file, .. to the directory containing it, and so on.

一个不太简洁/精确的答案:`from ... import`与`import.

For a less concise / more precise answer : `from ... import` vs `import .`

这篇关于如何理解.导入python吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆