创建具有多级文件夹的python包

问题描述 投票:-1回答:2

我想创建一个我的python代码包。我的文件夹结构如下:

sing*(this is a folder)*
--ml*(this is a folder)*
----regression*(this is a folder)*
------linear.py*(this is a class file with functions in it)* 
----classification*(this is a folder)*
------logistic.py*(this is a class file with functions in it)* 

我想通过以下方式访问linear.py中的类:

from sing.ml.regression import linear

请建议如何创建这样的包

提前致谢

python
2个回答
3
投票
sing
    __init__.py
    -ml
        __init__.py
        -regression
           __init__.py
           linear.py

        -classification
           __init__.py
           logistic.py

如果应用程序的工作目录不是唱歌的父文件夹,那么你需要将文件夹'sing'注册到PYTHONPATH环境变量中。

要从sing文件夹导入线性,您可以使用相对路径:

from ml.regression import linear

并且对于调用线性文件的功能,您可以使用:

linear.<*functionname*>(...)

1
投票

您需要在每个文件夹中添加__init__.py文件,以便python将其他* .py文件(和文件夹)解释为包。一个空文件就足够了。

© www.soinside.com 2019 - 2024. All rights reserved.