python - 自定义Python模块结构

标签 python python-3.x

我目前正在做一个个人编码项目,我正在尝试构建一个模块,但我不知道为什么我的结构不能按预期的方式工作:

\mainModule
    __init__.py
    main.py
    \subModule_1
        __init__.py
        someCode_1.py
        someCode_2.py
    \subModule_2
        __init__.py
        otherCode.py

我希望能够从 main.py 运行以下代码:

>>> from subModule_1 import someCode_1
>>> someCode_1.function()
"Hey, this works!"
>>> var = someCode_2.someClass("blahblahblah")
>>> var.classMethod1()
>>> "blah blah blah"
>>> from subModule2 import otherCode
>>> otherCode("runCode","#ff281ba0")

但是,例如,当我尝试导入 someCode_1 时,它会返回 AttributeError,我不太确定为什么。与__init__.py文件有关吗?

修订

  • 最小、完整且可验证(我希望......)

    \mainDir
        __init__.py # blank file
        main.py
        \subDir
            __init__.py # blank file
            codeFile.py
    

    使用这个...

    #main.py file
    import subDir
    subDir.codeFile.function()
    

    还有这个...

    #codeFile.py file
    def function():
        return "something"
    

    ...它返回与上面提到的相同的问题**。

** 确切的错误是:

Traceback (most recent call last):
  File "C:\...\mainDir\main.py", line 2, in <module>
    subDir.codeFile.function()
AttributeError: module 'subDir' has no attribute 'codeFile'

感谢@jonrsharpe:感谢您向我展示如何正确使用 Stack Overflow。

最佳答案

您有两种选择来完成这项工作。

要么这个:

from subdir import codeFile
codeFile.function()

或者:

import subdir.codeFile
subdir.codeFile.function()

关于python - 自定义Python模块结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41666188/

相关文章:

python - python3.0 的 Concat() 交替组

python - 尽管使用线程,函数执行还是卡住了 GUI

python - 使用变量构造一个长的 Python 字符串

python - 不断收到 ValueError : not enough values to unpack (expected 2, 得到 1)

python - 从 Postgres 中提取数据,并将其显示在模板中

TypeError : a bytes-like object is required, 不是 'str' 的 Python struct.unpack 错误

python - Google chrome 与 selenium 一起启动后立即关闭

生成自定义类集合的 Pythonic 多重继承

python - 何时在 GAE 中使用 try/except block

python - 使用 Python 字典通过 Plotly Express 创建条形图