<p>假设要以字符串形式传入类名,请尝试以下操作:</p>
<pre><code>def GenerateCharacter(Type, Number):
i=0
while i < (Number):
if Type == "Goblin":
TempChar = Goblin()
elif Type == "Imp":
TempChar = Imp()
# Etc. for every type of monster you have
Character_List.append(TempChar)
i += 1
</code></pre>
<p>也许有更好的方法可以做到这一点,将Goblin和Imp类型封装在一个Monster类中,这可能会使您的代码更易于维护。有关更多信息和示例,请参见此处:<a href="http://python-3-patterns-idioms-test.readthedocs.io/en/latest/Factory.html" rel="nofollow">http://python-3-patterns-idioms-test.readthedocs.io/en/latest/Factory.html</a></p>
<p>编辑:这里更接近你想要的:</p>
<pre><code>list_of_monsters = []
class Foo:
def __init__(self):
print "foo created"
class Bar:
def __init__(self):
print "bar created"
class Fubar:
def __init__(self, num, word):
print "Fubar created"
self.number = num
self.phrase = word
def create_monster(class_name, *args):
local_class = class_name(*args)
list_of_monsters.append(local_class)
create_monster(Foo)
create_monster(Bar)
# You can even pass in arguments:
create_monster(Fubar, 1, "Hello")
print list_of_monsters
</code></pre>
<p>如果你检查这段代码,你会看到怪物列表将包含3个对象,每个类一个。你知道吗</p>