I'm generating objects from a class. One of the, optional, attributes is a number. When no number is passed, I want to generate a random one. Unfortunately, when using numpy rand it seems a single random number is chosen and used for all future objects.
Below there's an example.
import numpy as np
class Class_1:
def __init__(self, num=np.random.rand()):
self.num = num
obj_1 = Class_1()
obj_2 = Class_1()
obj_3 = Class_1()
>>> obj_1.num
0.4664677766265517
>>> obj_2.num
0.4664677766265517
>>> obj_3.num
0.4664677766265517
I could use
obj_1 = Class_1(np.random.rand())
obj_2 = Class_1(np.random.rand())
obj_3 = Class_1(np.random.rand())
but that's not very pretty.
Aucun commentaire:
Enregistrer un commentaire