带有子模块和函数的 Python 模块 [英] Python modules with submodules and functions
问题描述
我有一个关于像 numpy 这样的库如何工作的问题.当我导入 numpy
时,我可以访问大量内置类、函数和常量,例如 numpy.array
、numpy.sqrt代码>等
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.
但是在 numpy 中还有其他子模块,例如 numpy.testing
.
But within numpy there are additional submodules such as numpy.testing
.
这是怎么做到的?以我有限的经验,带有子模块的模块只是带有 __init__.py
文件的文件夹,而带有函数/类的模块是实际的 python 文件.如何创建模块文件夹"?也有函数/类?
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?
推荐答案
包含 .py
文件和 __init__.py
的文件夹称为 package代码>.包含类和函数的文件之一是
module
.文件夹嵌套可以给你子包.
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
我可以导入 mypackage.module_a
或 mypackage.mysubpacakge.module_c
等等.
I could import mypackage.module_a
or mypackage.mysubpacakge.module_c
and so on.
您还可以通过将该代码放置在 __init__.py
中来将函数添加到 mypackage
(如您提到的 numpy 函数).虽然这通常被认为是丑陋的.
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.
如果你看看 numpy 的 __init__.py
你会在那里看到很多代码——其中很多是定义这些顶级类和函数.__init__.py
代码是加载包时执行的第一件事.
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 模块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!