问题描述
我对如何使用numpy工作的图书馆有疑问。当我导入numpy时,我可以访问许多内置的类,函数和常量,例如numpy.array,numpy.sqrt等。
但是在numpy还有其他的子模块,比如numpy.testing。
这是如何完成的?在我有限的经验中,带有子模块的模块只是带有 init .py文件的文件夹,而具有函数/类的模块则是实际的python文件。如何创建一个也有函数/类的模块文件夹?
一个包含的文件夹
.py 文件和 __ init __。py
被称为 package
。其中一个包含类和函数的文件是 module
。 例如,如果我有以下结构:
mypackage
__init__.py
module_a.py
module_b.py
mysubpackage
__init__.py
module_c.py
module_d.py
我可以导入 mypackage.module_a
或 mypackage.mysubpacakge.module_c
等等。
您也可以将函数添加到<$ c $通过将该代码放入 __ init __。py
中,可以使用c> mypackage (就像你提到的numpy函数)。虽然这通常被认为是丑陋的。
如果你看你会看到很多代码 - 其中很多是定义这些顶级类和函数。 __ init __。py
代码是加载包时首先执行的代码。
I had a question on how libraries like numpy work. When I import numpy, I'm given access to a host of built in classes, functions, and constants such as numpy.array, numpy.sqrt etc.
But within numpy there are additional submodules such as numpy.testing.
How is this done? In my limited experience, modules with submodules are simply folders with a init.py file, while modules with functions/classes are actual python files. How does one create a module "folder" that also has functions/classes?
A folder with .py
files and a __init__.py
is called a package
. One of those files containing classes and functions is a module
. Folder nesting can give you subpackages.
So for example if I had the following structure:
mypackage
__init__.py
module_a.py
module_b.py
mysubpackage
__init__.py
module_c.py
module_d.py
I could import mypackage.module_a
or mypackage.mysubpacakge.module_c
and so on.
You could also add functions to mypackage
(like the numpy functions you mentioned) by placing that code in the __init__.py
. Though this is usually considered to be ugly.
If you look at numpy's __init__.py
you will see a lot of code in there - a lot of this is defining these top-level classes and functions. The __init__.py
code is the first thing executed when the package is loaded.
这篇关于具有子模块和功能的Python模块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!