lundi 4 février 2019

Randomly pick out and change variable of class instance

I have a class with multiple variables, and I would like to randomly pick out one of its variables and change it. To pick out my variable I use the fact that every class instance has a dictionary and the random package;

import random as rnd
import chromosome as Chromosome

instance1 = Chromosome() #creates class instance
random_key = rnd.choice([instance1.__dict__]) #picks out random key

instance1.random_key = 5 #change the value of the random key

The last row obviously doesn't work, but I'm wondering if there's any way to get that functionality? I tried using the format function, but that didn't work.

Another solution could be to pick out a random number between 0 to the length of my dictionary. I could manually write out every variable change that I want to do, but only change one of them depending on what the random number is, it could look something like this;

import random as rnd
import chromosome as Chromosome

instance1 = Chromosome() #creates class instance
which_var_to_change = rnd.randint(1,len(instance1.__dict__)) #the for loop below works as if the length is 2
counter = 1

for key, value in instance1.__dict__.items():
    if key == 'first_variable' and counter > which_var_to_change:
        instance1.first_variable = 5 #change the value of the random key
    if key == 'second_variable' and counter > which_var_to_change:
        instance1.second_variable = 5 #change the value of the random key
    counter += 1

The problem with this solution is that if I have too many variables, it's gonna get crazily messy.




Aucun commentaire:

Enregistrer un commentaire