简体   繁体   English

带有子模块和函数的 Python 模块

[英]Python modules with submodules and functions

I had a question on how libraries like numpy work.我有一个关于像numpy这样的库如何工作的问题。 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.arraynumpy.sqrt等。

But within numpy there are additional submodules such as numpy.testing .但是在 numpy 中还有其他子模块,例如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.以我有限的经验,带有子模块的模块只是带有__init__.py文件的文件夹,而带有函数/类的模块是实际的 python 文件。 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 .包含.py文件和__init__.py文件夹称为package One of those files containing classes and functions is a module .包含类和函数的文件之一是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.我可以导入mypackage.module_amypackage.mysubpacakge.module_c等等。

You could also add functions to mypackage (like the numpy functions you mentioned) by placing that code in the __init__.py .您还可以通过将该代码放在__init__.py来向mypackage添加函数(如您提到的 numpy 函数)。 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.如果您查看numpy 的__init__.py您会看到其中有很多代码 - 其中很多是定义这些顶级类和函数。 The __init__.py code is the first thing executed when the package is loaded. __init__.py代码是加载包时执行的第一件事。

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

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