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

2024-04-30 05:36:44 发布

您现在位置:Python中文网/ 问答频道 /正文

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

输出通常是这样的。 ruby=[G,U,B,N,N,G] jaune=[G,U,B,N,N,G]

我想要的输出是这样的。 ruby=[R,A,N,R,N,B] jaune=[W,N,W,N,na]

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()


1条回答
网友
1楼 · 发布于 2024-04-30 05:36:44

使用构造函数和self值。您的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

相关问题 更多 >