为什么随机生成的数字序列对于不同的 class 个实例是相同的?

Why are random generated sequences of numbers the same for different class instances?

我一直在尝试生成不同的字典结构(与 Python 中不同的 class 实例相关),并在 [0, 1] 之间填充随机数值。字典的键不是那么重要。但是,主要问题是,当我尝试使用随机值生成字典时,它们都以相同的顺序出现:

{'p0': 0.8834439890229875, 'p1': 0.4542011548977558, 'd0': 0.041855079212439805, 'c0': 0.30179244567633823, 'c1': 0.026356543619428408, 'c2': 0.24603169392476631}
{'p0': 0.8834439890229875, 'p1': 0.4542011548977558, 'd0': 0.041855079212439805, 'c0': 0.30179244567633823, 'c1': 0.026356543619428408, 'c2': 0.24603169392476631}
{'p0': 0.8834439890229875, 'p1': 0.4542011548977558, 'd0': 0.041855079212439805, 'c0': 0.30179244567633823, 'c1': 0.026356543619428408, 'c2': 0.24603169392476631}

代码:

''' Individual Class '''

from random import Random

class Individual:

        chromosome = {} #The chromosome of an individual is a random generated dictionary.
        randomInstance = Random(datetime.now())

        def __init__(self, numP, numD, numC):
                self.randomInstance.seed()
                for i in range(numP):
                        plant = "p"
                        plant += str(i)
                        self.chromosome[plant] = self.randomInstance.random()

                for j in range(numD):
                        plant = "d"
                        plant += str(j)
                        self.chromosome[plant] = self.randomInstance.random()

                for k in range(numC):
                        plant = "c"
                        plant += str(k)
                        self.chromosome[plant] = self.randomInstance.random()

def main():

        list = []
        for i in range(4):
                inst = Individual(2, 1 ,3)
                list.append(inst.chromosome)

        print(list)

我正在尝试为每个 class 个实例获取不同的序列。

希望有人能提供帮助。谢谢大家

您将 chromosomerandomInstance 声明为 class 属性,以便它们在 class 的所有实例之间共享。如果您希望每个实例都使用它,则将它们初始化为 init 中的 class 属性。