如何构建包以使其模块可调用?

时间:2018-06-04 20:57:34

标签: python

我是Python的新手,我正在学习软件包和模块是如何工作的,但却遇到了麻烦。最初我创建了一个非常简单的包作为Lambda函数进行部署。我在根目录中有一个名为lambda.py的文件,其中包含handler函数,我将大部分业务逻辑放在一个单独的文件中。我创建了一个子目录 - 对于这个例子,让我们说它被称为testme - 更具体地说,它放在__init__.py下面的子目录下。最初这很有效。在我的lambda.py文件中,我可以使用此import语句:

from testme import TestThing # TestThing is the name of the class

然而,现在代码正在增长,我已经把东西分成了多个文件。结果,我的代码不再运行;我收到以下错误:

TypeError: 'module' object is not callable

这是我的代码现在的简化版本,用于说明问题。我错过了什么?我该怎么做才能制作这些模块"可调用"?

/lambda.py:

#!/usr/bin/env python2
# -*- coding: utf-8 -*-
from testme import TestThing


def handler(event, context):
    abc = TestThing(event.get('value'))
    abc.show_value()


if __name__ == '__main__':
    handler({'value': 5}, None)

/ TESTME / __ INIT __ PY:

#!/usr/bin/env python2
# -*- coding: utf-8 -*-
__project__ = "testme"
__version__ = "0.1.0"
__description__ = "Test MCVE"
__url__ = "https://stackoverflow.com"
__author__ = "soapergem"
__all__ = ["TestThing"]

/testme/TestThing.py:

#!/usr/bin/env python2
# -*- coding: utf-8 -*-


class TestThing:

    def __init__(self, value):
        self.value = value

    def show_value(self):
        print 'The value is %s' % self.value

就像我说的,我做这一切的原因是因为真实世界的例子有足够的代码我想把它分成子目录里面的多个文件。所以我在那里留下了一个__init__.py文件,只是作为一个索引。但我不确定包结构的最佳实践,或者如何使其工作。

1 个答案:

答案 0 :(得分:3)

您必须在__init__文件中导入您的课程:

<强> TESTME / __初始化__吡啶

from .TestThing import TestThing

或使用完整路径导入它:

<强> lambda.py

from testme.TestThing import TestThing

当您使用__init__.py文件时,您创建了一个包,并且此包(以根目录命名,例如testme,可能包含子模块。这些可以通过package.module语法访问,但是只有在那里明确导入子模块时,子模块的内容才会在根包中显示。