0

I've just started learning Python recently and the first project I'm making is a text based adventure game however I've run into a problem. I need a function that makes more objects using the class Goblin that are named after a string.

def spawn(name):
    title = name
    exec("{0} = {1}".format('title', Goblin))
    return title, 'spawn'

Essentially, another function calls this function to create another Goblin (a class) using the input name(a string) as the name of the new Goblin.

What I don't under stand though is that when I run the code(using "bill" as the argument), it gives me this error.

bill = <class '__main__.Goblin'>
       ^
SyntaxError: invalid syntax

Shouldn't my function be equivalent to:

bill = Goblin
  • 1
    Possible duplicate of [How can you dynamically create variables in Python via a while loop?](http://stackoverflow.com/questions/5036700/how-can-you-dynamically-create-variables-in-python-via-a-while-loop) – Padraic Cunningham Oct 10 '16 at 20:41

1 Answers1

0

When you do this:

exec("{0} = {1}".format('title', Goblin))

format method converts Goblin class by calling default __str__ method which yields <class '__main__.Goblin'>

Do this instead:

exec("{0} = {1}".format('title', 'Goblin'))

Wait! don't to this, just do:

title = Goblin

as it's strictly equivalent (without any security issues :)).

But that will just alias Goblin class to title. No real interest to all this after all (unless you want to create an instance?: title = Goblin())

With your comment: "I want a Goblin that is named after the string which title represents" I get it: you need

exec("{0} = {1}".format(title, 'Goblin()'))

(no quotes for the first arg so the name you're passing is used, and () on the second to create an instance)

Again: this is really a clumsy way of doing it. What if you want to iterate through all your goblins?

It would be much better to create a dictionary:

goblins_dict = dict()
goblins_dict["my_goblin"] = Goblin()
goblins_dict["my_goblin_2"] = Goblin()

and so on...

Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219