在python中从name实例化一个类

时间:2015-05-04 18:51:55

标签: python

我有以下文件架构:

[X] publisher/
    [X] __init__.py (containing Publisher(Object), an abstractclass)
    [X] mail.py (containing class Mail(Publisher))
    [X] simple.py (containing class Simple(Publisher))
    [X] ftp.py (containing class Ftp(Publisher))
[X] app.py

在app.py中我得到了这本词典:

publisher_to_load = ["Mail","Mail","Simple"]

我想为每个publisher_to_load实现相应的发布商。

我试过了:

import publisher
for name in publisher_to_load:
    getattr(publisher, name)()

但是我收到了错误

AttributeError: 'module' object has no attribute 'Simple'

有什么想法吗?

1 个答案:

答案 0 :(得分:0)

As may have been mentioned, your problem is the imports in __init__.py. That should solve your problem. However, given the general title of the question I will also note a few more things for anyone else. First of all, if you do in fact think you have to have to make things import each other like in the question alex referenced, first consider a better option to make two programs cooperate. If you need two-way communication, open up a socket or design some other kind of intermediary hand-off of information, two programs importing each other is a truly messy way to make two modules cooperate. Secondly, accessing variable names with strings should be avoided if possible. Especially in this case, that is not how handling imports should work. That being said, gatattr (or object.__dict__[]) like the question uses should work just fine.