After reading this answer, I understand that variables outside of __init__
are shared by all instances of the class, and variables inside __init__
are unique for every instance.
I would like to use the variables that are shared by all instances, to randomly give my instance of the class a unique parameter. This is a shorter version of what I've tried;
from random import choice
class Chromosome(object):
variable1 = [x for x in range(1,51)]
variable2 = [x for x in range(51,101)]
def __init__(self):
self.var1 = choice(variable1)
self.var2 = choice(variable2)
My problem is that I can't reach the instance variables when initializing a new instance, the error message says name "variable1" is not defined
, is there anyway to get around this?
EDIT: The reason I want to create the lists outside of the __init__
is to save memory, if I create 10.000 chromosomes with around 10-15 variables each, then it's better if I just create the lists once, instead of creating them for every chromosome.
EDIT2: If anyone wants to use it, my final solution involved using random.randrange(a,b+1,2)
. This picks out a random number (only even numbers) in the range [a,b], including the boundaries.