Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Selecting random class in Python

Tags:

python

oop

class

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.

like image 321
Stuart Lacy Avatar asked Feb 09 '26 18:02

Stuart Lacy


2 Answers

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()
like image 123
thefourtheye Avatar answered Feb 12 '26 07:02

thefourtheye


To handle the user input, just store your classes in a dictionary:

animals = {'dog': Dog, 'cat': Cat, 'pig': Pig}

You will then be able to pick the proper class and create an instance with:

animal = animals[user_input]()

If you need to be able to pick an animal at random or an animal from a user choice, you can combine this technique with the random.choice one:

animal = random.choice(animals.values())()
like image 24
tawmas Avatar answered Feb 12 '26 06:02

tawmas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!