[英]How do you import a list of classes from a module?
Is there a way to import only a specific, predefined list of classes from a Python module? 有没有办法从Python模块中仅导入特定的预定义类列表? For example, say that I had modules a.py
and b.py
in the same directory with the following code: 例如,假设我在同一目录中具有以下代码的模块a.py
和b.py
:
#a.py
class Foo(object):
'''definition of class Foo goes here'''
class Bar(object):
'''definition of class Bar goes here'''
aTypes = [Foo, Bar]
_ _
#b.py
from a import aTypes
print Foo
Running b.py
causes, of course, the print Foo
line to raise a NameError
. 当然,运行b.py
会使print Foo
行引发NameError
。 I didn't really think that this would work (the import statement in b.py
gives me an a.Foo
type instead of a Foo
type), but I can't figure out the right syntax. 我真的不认为这会起作用( b.py
的import语句为我提供了a.Foo
类型而不是Foo
类型),但是我找不到正确的语法。 Is there an alternative to from a import aTypes
that gives the desired behavior? 有没有替代from a import aTypes
,可以提供所需的行为?
You could import the names directly: 您可以直接导入名称:
from a import Foo, Bar
Alternately, you could define __all__
in a.py
: 或者,您可以在a.py
定义__all__
:
__all__ = ['Foo', 'Bar']
and then do a wildcard import in b.py
: 然后在b.py
进行通配符导入:
from a import *
For just two names though, it would be easier to use the first solution. 不过,仅使用两个名称,使用第一个解决方案会更容易。
Supposing you really do need to do this (deal with list of types) and can't use tricks like __all__
that only work once (one such special list per module), then: 假设您确实确实需要执行此操作(处理类型列表),并且不能使用仅工作一次的__all__
之类的技巧(每个模块一个这样的特殊列表),然后:
def gettypes(types):
thismodule = sys.modules[__name__]
for t in types:
setattr(thismodule, t.__name__, t)
Use it like this: 像这样使用它:
import a
gettypes(a.aTypes)
I'm finding it difficult to imagine why you'd need this, but that's not my problem ;-) 我很难想象您为什么需要这个,但这不是我的问题;-)
Note the use of __name__
means this doesn't work for symbols in general, only for classes, modules, functions and anything else I've forgotten (or at a pinch for objects of your own design that have a __name__
). 请注意,使用__name__
意味着这通常不适用于符号,仅适用于类,模块,函数和我忘记的任何其他内容(或者对于您自己设计的具有__name__
对象也很__name__
)。 It also won't work for things you've aliased in the module, for example by writing Baz = Bar
in the module and then using Baz
in the list. 它也不适用于您在模块中别名的事情,例如,通过在模块中编写Baz = Bar
,然后在列表中使用Baz
来实现。 If the list was ['Foo', 'Bar']
instead of [Foo, Bar]
, and you also passed the source module into gettypes
, then you could avoid those restrictions. 如果列表是['Foo', 'Bar']
而不是[Foo, Bar]
,并且您还将源模块传递给gettypes
,则可以避免这些限制。
You can define __all__
at the module level of a.py
: 您可以在a.py
的模块级别定义__all__
:
__all__ = ['Foo', 'Bar']
This will allow you to import it in the following way: 这将使您可以通过以下方式导入它:
from a import *
Of course, this behaviour isn't always encouraged, and the alternative is preferred: 当然,并非总是鼓励这种行为,因此首选替代方法:
from a import Foo, Bar
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.