【发布时间】:2012-04-26 21:28:14
【问题描述】:
Python 的导入功能有时仍然让我感到困惑。这是一个例子:
我的项目有以下包结构:
Project/
src/
example/
__init__.py
an_example.py
top/
__init__.py
lin/
__init__.py
factory.py
在an_example.py,我想写
from top import lin
if __name__ == '__main__':
a = lin.factory.AClass()
但是,这失败了:
a = lin.factory.AClass()
AttributeError: 'module' object has no attribute 'factory'
an_example.py 可以这样写:
from top.lin import factory
if __name__ == '__main__':
a = factory.AClass()
你能解释一下为什么像第一个版本那样写导入语句是错误的吗?我更喜欢像lin.factory.AClass 这样的完全限定名称而不是factory.AClass。
【问题讨论】:
标签: python python-3.x package