我今天在玩Python,尝试创建自己的模块。看起来我并不完全理解Python命名空间,我想知道是否有人能回答我关于它们的问题。有关Python命名空间和使用导入的问题
这里是我做了什么一个例子:我创建了一个名为mytest的结构如下模块
:
mytest/
....setup.py
....bin/
....docs/
....mytest/
........__init__.py
........test.py
....tests/
test.py包含一个方法如下:
def say_hello():
print "Hello"
我已经通过distutils安装了mytest。使用'点子列表'我可以看到模块已安装。
所有确定,但现在我想要使用它。我创建了一个测试脚本moduletest.py:
from mytest import test
test.say_hello()
并且运行正常,打印'Hello'消息。我对此感到满意,并开始使用导入模块的其他方法。
下似乎都工作确定:
from mytest.test import say_hello
say_hello()
和:
import mytest.test as test
test.say_hello()
但是,以下将不起作用:
import mytest
test.say_hello()
和:
import mytest
mytest.test.say_hello()
和:
import mytest.test
test.say_hello()
任何人都可以解释为什么你不能导入整个mytest的模块,然后用你想要的部分,或者你为什么要别名测试(进口mytest.test作为测试),以访问它而不是只导入mytest.test(导入mytest.test)?
我想我的理解有点偏离,但一些解释会真的有所帮助。 谢谢!
这使得更多的意义!我认为这个软件包是模块,并且是顶级命名空间。非常感谢! – steveYeah