Selecting random class in Python

class, oop, python

Solution

Instead of storing the strings of class names, store the actual classes itself, like this

animals = (Dog, Cat, Pig)
the_chosen_one = random.choice(animals)
new_animal = the_chosen_one()

Problem

Say you have classes Dog, Cat, Pig etc... that all inherit from Animal, what's the best way to randomly initialise one? I.e. a basic way would be to have a tuple, select an item from it and then make an instance of the selected value. ``` animals = ('dog', 'cat', 'pig'...) choice = random.choice(animals) if choice == 'dog': new_animal = Dog() elif choice == 'cat': new_animal = Cat() ... ``` But obviously this is very inefficient, how would it be best to implement this behaviour? On a related note, if you ask the user to input (either stdin, textfile, and so on) their desired animal, how would you then instantiate the correct animal then? Again an ugly way to do it would be a big if, elif statement as above.

Original source