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
那里留下了一个文件,基本上只是作为一个索引。但我非常不确定包结构的最佳实践是什么,或者如何让它发挥作用。
解决方案
您要么必须在文件中导入您的课程__init__
:
testme/__init__.py:
from .TestThing import TestThing
或使用完整路径导入:
lambda.py:
from testme.TestThing import TestThing
当你使用一个__init__.py
文件时,你创建了一个包,这个包(以根目录命名,例如 testme,可能包含子模块。这些可以通过package.module
语法访问,但子模块的内容只有在根包中可见,如果你在那里显式导入它们。
推荐阅读
- typo3 - Typo3 9.5:语言回退不适用于网格元素
- javascript - 安装后的 Npm 错误
- sql - 如何在sql中使用分区获取最小值和最大值
- reactjs - twilio 设备连接和重新连接
- c# - 如何在 Rest 请求中包含代理服务器身份验证?
- flutter - 如何解决地图颤振中不稳定的折线
- flutter - Flutter:参数类型'LayoutGrid'不能分配给参数类型'Widget?'.dartargument_type_not_assignable
- c# - 是否可以在第一次打开表单后修改 onload 事件?
- c - 如何在C中将字符串与for进行比较
- typo3 - 在 TYPO3 的生产系统上部署期间刷新缓存(基于 Composer 的安装)