导入和结构化 Python 模块/类

2 投票
2 回答
1482 浏览
提问于 2025-04-16 08:18

我正在谷歌应用引擎上做一些基础的Python工作,但我不知道该如何正确地组织我的处理程序。

  • /main.py
  • /project/handlers/__init__.py
  • /project/handlers/AccountHandler.py

AccountHandler基本上是一个类。

class AccountHandler(webapp.RequestHandler):

当我使用从project.handlers导入AccountHandler时,Python总是给我一个错误:

TypeError: 'module' object is not callable

我该如何命名/导入/组织我的类呢?

谢谢,

马丁

2 个回答

0

你需要把 init.py 改名为 __init__.py

6

引用一下官方文档的内容:

模块就是一个包含Python定义和语句的文件。文件名就是模块名,后面加上后缀.py

在这个例子中,你导入的AccountHandler就是模块/project/handlers/AccountHandler.py。文件AccountHandler.py本身不能直接调用,解释器会告诉你这一点。要调用你在文件中定义的类,只需要使用:

from project.handlers.AccountHandler import AccountHandler
# Alternately
# from project.handler import AccountHandler
# AccountHandler.AccountHandler() # will also work.

撰写回答