ZaruStarru
ZaruStarru

Reputation: 21

Is it possible to select a random variable from a class?

This is an example of something I want to do:


import random

class example_Class(object):

  def __init__(self, firstvar, secondvar, thirdvar):
    self.firstvar = firestvar
    self.secondvar = secondvar
    self.thirdvar = thirdvar

variable_1 = example(1, 2, 3)

variable_2 = example(4, 5, 6)

variable_3 = example(7, 8, 9)

random_var = (random.choice(example_Class))

Ideally, then, random_var would be assigned as equal to either variable_1, variable_2, and variable_3. But this doesn't work because I have no idea what the syntax for this would be. Any help?

Upvotes: 0

Views: 264

Answers (1)

chepner
chepner

Reputation: 531265

random.choice expects a sequence of some type. I would define a specific method to use to produce one from the data in your object.

 class ExampleClass:
     @property
     def values(self):
         return [self.firstvar, self.secondvar, self.thirdvar]

Then you can write

e = ExampleClass()
random_var = random.choice(e.values)

Upvotes: 1

Related Questions