随机挑选并更改类实例的变量

时间:2019-02-04 18:17:08

标签: python-3.x random instance-variables

我有一个带有多个变量的类,我想随机选择一个变量并进行更改。为了选择变量,我使用了每个类实例都有一个dictionaryrandom包的事实。

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

最后一行显然行不通,但是我想知道是否有任何方法可以获取该功能?我尝试使用格式函数,但这没用。

另一种解决方法是选择一个介于0到我的字典长度之间的随机数。我可以手动写出我想做的每个变量更改,但是只能根据随机数更改其中之一,它看起来像这样;

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

此解决方案的问题是,如果我有太多的变量,它将变得非常混乱。

1 个答案:

答案 0 :(得分:0)

从类实例中选择一个随机变量并对其进行更改(其中Chromosome是类);

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