难以为每个父对象生成唯一的数组

问题描述 投票:0回答:1

我正在为游戏制作基因模拟器,当我调用函数填充确定父母基因的数组时,它会为每个父母提供相同的输出。

输出通常看起来像这样。红宝石= [G,U,B,N,N,G]jaune = [G,U,B,N,N,G]

我想要的输出将是这样的。红宝石= [R,A,N,R,N,B]jaune = [W,N,W,N,N A]

import random
import time

class Parent():
    magic = [None, None, None, None, None, None]


    types = ['B', 'U', 'W', 'R', 'G', 'N', 'A']
    def gen(self):
        for i in range(0, 6):
            self.magic[i] = self.types[random.randint(0, 6)]


    def traits(self):
        print (self.magic)



jaune = Parent()
ruby = Parent()

jaune.gen()
ruby.gen()

jaune.traits()
ruby.traits()

python random
1个回答
3
投票

使用构造函数和自身值。您的magic是全局变量。

import random
import time

types = ['B', 'U', 'W', 'R', 'G', 'N', 'A']

class Parent():
    def __init__(self):
        self.magic = []
        self.gen()

    def gen(self):
        for i in range(0, 6):
            self.magic.append(types[random.randint(0, 6)])

    def traits(self):
        print (self.magic)


jaune = Parent()
ruby = Parent()

jaune.traits()
ruby.traits()

此外,您也可以在__init__内部生成值。

检查

  • Setters / Getters
  • 局部/全局变量
  • 当值对应于特定类而不是静态方法时,请使用self
© www.soinside.com 2019 - 2024. All rights reserved.