我正在为游戏制作基因模拟器,当我调用函数填充确定父母基因的数组时,它会为每个父母提供相同的输出。
输出通常看起来像这样。红宝石= [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()
使用构造函数和自身值。您的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__
内部生成值。
检查
self