为什么“ __all__”对“导入*”没有理想的效果?

问题描述 投票:3回答:3

文件结构:

./__init__.py
  a.py
    /lib
    __init__.py
    Foo1.py # contains `class Foo1`
    Foo2.py # contains `class Foo2`
    # so on ...

a.py中对此进行了测试,并为此做了工作;

from lib.Foo1 import Foo1
from lib.Foo2 import Foo2

但是,当我执行from lib import *时,__all__ = ["Foo1", "Foo2"]中的__init__.py无效。

错误:<type 'exceptions.TypeError'>: 'module' object is not callable

我想念的是什么?

这里是a.py

#!/usr/bin/python 

import cgi, cgitb
cgitb.enable()

from lib import *

print "Content-Type: text/html"
print ""
print "Test!"

foo1 = Foo1()
foo2 = Foo2() 

使用了这些参考:http://docs.python.org/2/tutorial/modules.html#importing-from-a-packageHow to load all modules in a folder?

python
3个回答
4
投票
from lib import *

lib中的所有内容导入当前模块,因此我们的globals()看起来像:

{'Foo1':<module lib.Foo1>,
 'Foo2':<module lib.Foo2>}

Whereas

from lib.Foo1 import *
from lib.Foo2 import *

使我们的globals()成为

{'Foo1':<class lib.Foo1.Foo1>,
 'Foo2':<class lib.Foo2.Foo2>}

因此,在第一种情况下,我们只是导入模块,而不是我们想要的模块中的类。


3
投票

将以下内容添加到.../lib/__init__.py文件:

from Foo1 import Foo1
from Foo2 import Foo1

__all__ = ['Foo1', 'Foo2']

注意,PEP-8建议使用package and modules names be all lowercase以避免混淆。


2
投票

[从包中导入*时(如您的情况,使用__all__中的init.py__all__指定应加载并导入到当前名称空间的所有模块。

因此,在您的情况下,from lib import *将导入模块Foo1Foo2,您需要像这样访问类:

foo1 = Foo1.Foo1()
foo2 = Foo2.Foo2()

快速查看Importing * in Python

© www.soinside.com 2019 - 2024. All rights reserved.