简体   繁体   English

了解导入X和从XY导入Z的区别

[英]Understanding the difference between import X and from X.Y import Z

This is very basic question which has a very extensive answer written by @Mark Roddy Use 'import module' or 'from module import'? 这是一个非常基本的问题,由@Mark Roddy编写,具有非常广泛的答案。 使用“导入模块”还是“从模块导入”?

According to this answer there are pros and cons to each method but the result is equivalent and both work. 根据这个答案,每种方法都有其优缺点,但结果是相同的,并且两者都可行。

so doing: 这样做:

import module

or 要么

from module import foo

should work. 应该管用。

My Question: 我的问题:

Consider this example: 考虑以下示例:

import distutils
print (distutils.util.strtobool('true'))

Which gives: 这使:

> Traceback (most recent call last):   File "<stdin>", line 1, in
> <module> AttributeError: module 'distutils' has no attribute 'util'

And: 和:

from distutils.util import strtobool
print (strtobool('true'))

Which gives following ouput: 给出以下输出:

1

So I'm confused. 所以我很困惑。 Both should work. 两者都应该起作用。 Why Python generates an exception for the first approach? 为什么Python为第一种方法生成异常?

If you import A , and then try to access AB , then B must be a valid attribute present in module A . 如果import A ,然后尝试访问AB ,则B必须是模块A存在的有效属性。 For instance: 例如:

# A.py
from . import B
# or
B = 'foo'

If A contains the above code, then inside A , B is a valid local name and by extension an accessible attribute of module A . 如果A包含上述代码,则AB内部是有效的本地名称,并且通过扩展可访问模块A的可访问属性。 However, if module A does not define any B , then you can't access it when you import A . 但是,如果模块A没有定义任何B ,则在import Aimport A无法访问它。

Now, import AB or from AB import ... explicitly looks not at the attributes of the modules, but at the files and folders. 现在, import ABfrom AB import ...显式地不查看模块的属性,而是查看文件和文件夹。 So even if inside A.py there's no symbol B defined, as long as there's a file B.py or folder B , import will import it. 因此,即使在A.py中没有定义符号B ,只要存在文件B.py或文件夹Bimport也会导入它。

These are equivalent: 这些是等效的:

from mod import val
val

import mod
mod.val

As are these: 这些是:

from mod1.mod2 import val
val

import mod1.mod2
mod1.mod2.val

But this doesn't work, as mod2 is not imported: 但这不起作用,因为未导入mod2

import mod1
mod1.mod2.val

If you add import mod2 inside mod1.py (or mod1/__init__.py ), then mod2 becomes a value exported by mod1 , and the last example will work. 如果在mod1.py (或mod1/__init__.py )中添加import mod2 ,则mod2成为mod1导出的值,最后一个示例将起作用。 distutils does not import distutils.util , so you have to import it yourself in order to gain access to its exported members. distutils不会导入distutils.util ,因此您必须自己导入它才能访问其导出的成员。

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

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