[英]what does importing a module in python mean?
I am new to python and found that I can import a module without importing any of the classes inside it. 我是python的新手,发现我可以导入模块而无需导入其中的任何类。 I have the following structure --
我有以下结构-
myLib/
__init__.py
A.py
B.py
driver.py
Inside driver.py I do the following -- 在driver.py内部,我执行以下操作-
import myLib
tmp = myLib.A()
I get the following error trying to run it. 我在尝试运行它时遇到以下错误。 AttributeError: 'module' object has no attribute A
AttributeError:“模块”对象没有属性A
Eclipse does not complain when I do this, in fact the autocomplete shows A when I type myLib.A. 当我这样做时,Eclipse不会抱怨,实际上,当我键入myLib.A时,自动完成功能会显示A。
What does not it mean when I import a module and not any of the classes inside it? 导入模块而不导入模块中的任何类是什么意思?
Thanks 谢谢
P P
Python is not Java. Python不是Java。
A
and B
are not classes. A
和B
不是类。 They are modules. 它们是模块。 You need to import them separately.
您需要分别导入它们。 (And
myLib
is not a module but a package.) (而且
myLib
不是模块,而是包。)
The modules A
and B
might themselves contain classes, which might or might not be called A
and B
. 模块
A
和B
本身可能包含类,这些类可能会也可能不会被称为A
和B
You can have as many classes in a module as you like - or even none at all, as it is quite possible to write a large Python program with no classes. 您可以根据需要在模块中拥有多个类-甚至根本没有类,因为编写没有类的大型Python程序很有可能。
To answer your question though, importing myLib
simply places the name myLib
inside your current namespace. 但是,要回答您的问题,导入
myLib
只是将名称myLib
放置在当前名称空间中。 Anything in __init__.py
will be executed: if that file itself defines or imports any names, they will be available as attributes of myLib
. __init__.py
任何内容都将执行:如果该文件本身定义或导入了任何名称,则它们将用作myLib
属性。
If you do from myLib import A
, you have now imported the module A
into the current namespace. 如果
from myLib import A
,则现在已将模块 A
导入到当前名称空间中。 But again, any of its classes still have to be referenced via the A
name: so if you do have a class A
there, you would instantiate it via AA()
. 但是同样,它的任何类仍然必须通过
A
名称进行引用:因此,如果那里确实有类A
,则可以通过AA()
实例化它。
A third option is to do from myLib.A import A
, which does import the class A
into your current namespace. 第三种选择是
from myLib.A import A
,它确实将类 A
导入到您当前的名称空间中。 In this case, you can just call A()
to instantiate the class. 在这种情况下,您只需调用
A()
即可实例化该类。
You need to do 你需要做
from mylib import A
Because A
is not an attribute of __init__.py
inside mylib
因为
A
不是mylib
中__init__.py
的属性
When you do import mylib
it imports __init__.py
当您
import mylib
它会导入__init__.py
See my answer. 看我的答案。 About packages
关于包装
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.