包导入库甚至没有初始化 class
package imports libraries without even intializing class
问题是如果从一个包中导入另一个包中的 class,就像这样:
from bar import foo
它会初始化 class 吗?如果模块在第一行有一个导入,如:
import tensorflow
class foo:
def __init__(self):
# some things
即使我们不从另一个文件初始化 class,它也会导入包吗?
Does it initialize the class?
不,它只是让您的程序访问那个 class - 准备好在您需要时实例化为一个对象(然后它会调用 __init__
方法)。
Does it import the package even if we don't initialize the class from another file?
是的。你可以看到这就好像你只是 import bar
,然后你就可以使用 bar.tensorflow
访问导入的 tensorflow 模块,即它实际上是导入的,即使有 nothing 模块中的其他内容。
在您只是从 bar
导入 foo
的特定情况下,我们仍然可以通过 inspect
内置包访问 tensorflow,这将为我们提供对 [=15] 的引用=] 因此 .tensorflow
来自 foo
.
import inspect
from bar import foo
print(inspect.getmodule(foo).itertools) #<module 'itertools' (built-in)>
我不确定是否有更简单的方法从 foo
"get at" bar
不使用 inspect
,但这就是我找到的目的是为了充分解释你的情况!
问题是如果从一个包中导入另一个包中的 class,就像这样:
from bar import foo
它会初始化 class 吗?如果模块在第一行有一个导入,如:
import tensorflow
class foo:
def __init__(self):
# some things
即使我们不从另一个文件初始化 class,它也会导入包吗?
Does it initialize the class?
不,它只是让您的程序访问那个 class - 准备好在您需要时实例化为一个对象(然后它会调用 __init__
方法)。
Does it import the package even if we don't initialize the class from another file?
是的。你可以看到这就好像你只是 import bar
,然后你就可以使用 bar.tensorflow
访问导入的 tensorflow 模块,即它实际上是导入的,即使有 nothing 模块中的其他内容。
在您只是从 bar
导入 foo
的特定情况下,我们仍然可以通过 inspect
内置包访问 tensorflow,这将为我们提供对 [=15] 的引用=] 因此 .tensorflow
来自 foo
.
import inspect
from bar import foo
print(inspect.getmodule(foo).itertools) #<module 'itertools' (built-in)>
我不确定是否有更简单的方法从 foo
"get at" bar
不使用 inspect
,但这就是我找到的目的是为了充分解释你的情况!