1

I want to be able to use the input string as the name of an instance, how can I do that?

eg.,

class Animal:
    def something():
        pass

x = input()     # input is "cat"
x = Animal()    # create as: cat = Animal()
print(cat.something())

The reason I want to do this is because I need to find & get data from this new instance later on in the code. Instances should be in a general tree:

├── cat
│   ├── lion
│   │   ├── giraffe
│   │   └── croc
│   ├── bull
│   └── mice
│                 
└── dog

Thanks

Dylan
  • 53
  • 4
  • 1
    You should be using a dictionary. Consider your code `print(cat.something())`? What if I had entered `turtle` instead of `cat`. How would you deal with that if `cat` is hard-coded into the program? – Mark Sep 27 '22 at 01:16
  • @Mark Non of the `cat` or `dog` or any names are hard-coded, they're all user given. The tree structure is also user defined. – Dylan Sep 27 '22 at 01:22
  • While it is strong not recommended, you can use `exec()`. Like this: `exec(f"{x} = Animal()")`. – Michael M. Sep 27 '22 at 01:22
  • @Michael This is a terrible idea, you will both make your code difficult to debug/maintain and vulnerable to random code injection from user input... – mozway Sep 27 '22 at 01:33
  • @mozway Yes, that is why it is strongly not recommended. – Michael M. Sep 27 '22 at 01:36
  • @Michael Then don't suggest it... There is no reason to suggest this kind of things to beginners, this would be the similar to suggest an amateur locksmith "*Although not recommended you could use dynamite to open your door*"... Except the dramatic effect will not be seen immediately. Just don't suggest that and explain how to use a dictionary. – mozway Sep 27 '22 at 01:38
  • @Mark Sorry I still dont get it, how do I do it with a dictionary if the key is user input and value is a class instance? – Dylan Sep 27 '22 at 01:46
  • @Dylan. The user input is the key. You make a dict. `animals = {}`. Then `x = input()` then `animals[x] = Animal()`. Now you can access all the things users input. using dict methods like `animals.keys()` and `animals.items()`. – Mark Sep 27 '22 at 01:49
  • Also @Dylan what I meant by hard-coded is you have `print(cat.something())`. If you didn't know what animal the user entered, what would you put in that print statement? – Mark Sep 27 '22 at 01:50
  • @Mark Ok I see, sort of like an array. How would that change the tree implementation? For eg. `cat.child() = lion` would become `animals.keys(cat).child() = animals.keys(lion)`? I have `self.name = name` and a getter method inside Animal class, I'm planning on using that to get the animal name – Dylan Sep 27 '22 at 02:31

0 Answers0