简体   繁体   中英

Mixing functions and subpackages in Python packages

Is there a way to mix subpackages and functions in my Python packages?

Currently, my layout is roughly like this:

lib/
   __init__.py
   Transform.py
   Statistic.py

where Transform.py and Statistic.py contain several functions each. To use them I do something like

from lib import Transform

Transform.fft(signal);

Now I would like to be able to have a function in a package inside Transform :

from lib.Transform import bins

Transform.bins.extent(signal);

Is that even possible? How would I have to define my packages to do that?

Solution #1: Try the following layout:

lib/
  __init__.py
  Statistic.py
  Transform
    __init__.py
    bins.py

In this case Transform.fft goes inside lib/Transform/__init__.py and Transform.bins.extent inside lib/Transform/bins.py

Solution #2: If you wish to keep __init__.py short and clean, you can also create a separate Python-module (like fft.py ) and import it in __init__.py as follows:

from fft import *

In which case you can also use:

from lib.Transform import fft

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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