-1

This may be a simple question but I haven't found the answer to this online anywhere. I want to take an argument or input and use that name to create an instance of a class. Is that possible?

Example:

def make_instance(argument):
    # argument = Something() | example if argument = "one", then
    # make instance would create-->  one = Something()
    # and I could do one.do_anything

class Something:
    def do_anything():
        print("anything")

Is this possible? Interpret the content of an argument and use it to create an instance of a class or a variable or anything for that matter. So long as the contents of the argument, whether int or str, becomes the name of the instance of class or name of variable?

  • 4
    As a general rule, making variable names out of data is a bad idea. If you absolutely have to do it, a dictionary of instance variables is the way to go. – TheSoundDefense Aug 09 '14 at 15:30
  • 2
    what are you trying to achieve? – Padraic Cunningham Aug 09 '14 at 15:33
  • I'm writing an app that reads text messages from Twilio. The app checks for an incoming number and takes that number to use it as an instance of a class I defined. So I want to take the phone # and instantiate it as an instance of a class. – user3925300 Aug 09 '14 at 15:40
  • Sounds like the phone # should be an attribute of whatever class you wish to instantiate -- and those instances will get stored in some sort of container class like a dictionary, list, etc. – martineau Aug 09 '14 at 18:21

1 Answers1

2

You probably want to do something like

instances = {}
key3 = 12345
instances["one"] = Something()
instances[2] = Something()  # another instance
instances[key3] = Something()  # and another one
jolvi
  • 4,463
  • 2
  • 15
  • 13
  • Hi and thank you for the answer. Again, this may be a super simple thing but I perhaps lack the terminology to ask the question correctly. So say my program checks twilio database and finds that a new text was received by number (800)123-4567. In that case, and by your example I would do: `instances[8001234567] = Something()` Correct? But now if I read the value of the number as a variable so: `new_number = client.list.sent_from() #stores the new # into new_number` then would this work: `instances[new_number] = Something()` ? – user3925300 Aug 10 '14 at 19:22
  • Yes, this seems OK. I edited the example accordingly. The "content of" `new_number` must be immutable (like an `int` is immutable). Of course, you also need to put some info into `Something()` such that all this makes sense. – jolvi Aug 11 '14 at 12:26
  • Thanks so much. Great help and answers exactly what I was looking for. Thanks again. – user3925300 Aug 11 '14 at 14:09