【问题标题】:creating python package with multiple level of folders创建具有多级文件夹的python包
【发布时间】:2018-02-28 08:28:36
【问题描述】:

我想为我的 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

请告知如何创建这样的包

提前致谢

【问题讨论】:

  • 我相信你已经可以从你使用绝对导入的地方访问线性
  • 我的消费者应用程序托管在 azure 上。
  • @Shinratensei,你是说如果我在“sing”文件夹中有一个 test.py 文件,那么在 test.py 中我可以通过说“sing.ml”来调用 linear.py 类。回归导入线性”?
  • 从我在其他问题中读到的内容,是的,你应该能够
  • 不,我收到以下错误“ValueError: Attempted relative import in non-package”

标签: python


【解决方案1】:
sing
    __init__.py
    -ml
        __init__.py
        -regression
           __init__.py
           linear.py

        -classification
           __init__.py
           logistic.py

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

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

from ml.regression import linear

对于线性文件的调用函数,你可以使用:

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

【讨论】:

  • error is "TypeError: 'module' object is not callable" 并且代码是 import os os.chdir("/Users/Documents/sing");从 ml.regression 导入线性 obj=Linear()
  • 即使我尝试 "linear.(...)" 并得到相同的错误
【解决方案2】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-01-08
    • 1970-01-01
    • 2015-11-27
    • 2011-12-25
    • 2012-01-19
    • 1970-01-01
    • 1970-01-01
    • 2020-10-27
    相关资源
    最近更新 更多