简体   繁体   English

Python:动态导入模块和对象

[英]Python: Dynamically import modules and objects

I want import dynamically some class through variable like:我想通过变量动态导入一些类,例如:

classes = ['AaaBc', 'AccsAs', 'Asswwqq']
for class in classes:
    from file.models import class

How can I do it ?我该怎么做?

Use __import__使用__import__

spam = __import__('spam', globals(), locals(), [], 0)

The statement import spam.ham results in this call:语句 import spam.ham 导致此调用:

spam = __import__('spam.ham', globals(), locals(), [], 0)

Note how __import__() returns the top-level module here because this is the object that is bound to a name by the import statement.请注意__import__()在这里如何返回顶级模块,因为这是由 import 语句绑定到名称的对象。

On the other hand, the statement from spam.ham import eggs, sausage as saus results in:另一方面, from spam.ham import eggs, sausage as saus的声明from spam.ham import eggs, sausage as saus导致:

_temp = __import__('spam.ham', globals(), locals(), ['eggs', 'sausage'], 0)
eggs = _temp.eggs
saus = _temp.sausage

see: https://docs.python.org/3/library/functions.html#__import_ _请参阅: https: //docs.python.org/3/library/functions.html#__import__

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM