Python: 无法从我的模块加载 class

Python: cannot load class from my module

编辑: 我无法使用自己的模块。这是愚蠢的浪费时间。如果您遇到同样的问题,请先尝试阅读以下内容: http://docs.python-guide.org/en/latest/writing/structure/

我刚开始使用 Python 进行 OOP,我对模块和 classes 感到困惑。

我使用 Mac 工作,我可以编写自己的模块并从 site-packages 文件夹中加载它们。

现在我想用有用的 classes 创建模块。 import custom_module 有效。 但是如果 custom_module 有一个 class Custom_class,事情就不行了。

我试过: (编辑:对不起,我正在删除编造的旧代码,这是我刚刚使用但不起作用的代码)

在custommodule.py中:

class Customclass:
    def __init__(self, name):
        self.name = name

此模块加载无误。 然后我得到:

new = custommodule.Customclass('foo')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'module' object has no attribute 'Customclass'

顺便说一句,我开始尝试使用 tutorial

中的代码来做到这一点

我无法克服这个问题。请指教,一定是我哪里做错了。

至少对我来说,这是有效的from mod_name import ClassName

当我 运行 这段代码时,我没有收到任何错误。希望这对您有所帮助

编辑:还要确保您要导入的模块在项目目录中。如果您查看图像中的左侧面板,两个模块都在 Stack 中。我希望这是显而易见的,但是 class 也需要在您导入的模块中。确保您正在导入的 class 不会导入您导入的 class,因为那样您会得到循环依赖。

试试这个方法

文件 custommodule.py 在目录 custommodule

class Customclass:
    def __init__(self, name):
        self.name = name

自定义模块目录中的文件__init__.py

from .custommodule import CustomClass

请注意自定义模块之前的点。这会强制 init 从同一目录加载模块。

没有点,它在 python2 下有效,但在 python3

下无效

使用此文件布局

site-packages/custommodule/__init__.py
site-packages/custommodule/custommodule.py

您正在创建一个名为 custommodule 的包,其中包含一个名为 的模块 custommodule。您的代码需要看起来像

import custommodule
# or more specifically,
# import custommodule.custommodule
new = custommodule.custommodule.Customclass('foo')

from custommmodule import custommodule
new = custommodule.Customclass('foo')

您也可以将 custommodule.py 直接放在 site-packages 中以避免创建包,在这种情况下您的原始代码应该可以工作。