Hello tutors,

This is something I've been trying to figure out for some time.  Is
there a way in Python to take a string [say something from a
raw_input] and make that string a variable name?  I want to to this so
that I can create class instances on-the-fly, using a user-entered
string as the instance name.  I can do it with an "exec" statement,
but that would force me to use more "execs" to reference the newly
created class instance[s] and I would rather not do that.  I'm sure I
could accomplish something similar using a plain old dictionary, but I
was playing around with the OOP stuff and thought it might be a neat
thing to try out.

I've attached the small function I've come up with to the end of this
message.  This is just a model I created for testing purposes, so it's
not the most elegant code.  Any suggestions would be greatly
appreciated.

TIA,

tony giunta

def generateInstance():
        class test:
                def __init__(self, title, price):
                        self.title = title
                        self.price = price
                def theTitle(self, title):
                        return self.title
                def thePrice(self, price):
                        return self.price
        
        myName = raw_input("Name: ")
        myTitle    = raw_input("Title: ")
        myPrice  = raw_input("Price: ")

        exec '%s = test("%s", %s)' % (myName, myTitle, myPrice)
_______________________________________________
Tutor maillist  -  [email protected]
http://mail.python.org/mailman/listinfo/tutor

Reply via email to