简体   繁体   English

对象实例作为列表元素

[英]Object instances as list elements

I've written the below on a whim after being reading about the "METHINKS IT IS LIKE A WEASEL" algorithm. 在阅读了有关“ METHINKS IT就像Weasel”算法之后,我心血来潮地写下了下面的内容。 What I expect to happen in pop_gen() is for ten instances of Gib to be created - each with a randomised name - and stored in the list popul. 我期望pop_gen()中发生的事情是要创建十个Gib实例-每个实例都有一个随机名称-并存储在列表popul中。 What I get instead is a list of instances with the same name. 我得到的是具有相同名称的实例列表。 I think that I'm actually only creating one instance then referring to it ten times, but I can't figure out why - I've tried doing it with a for loop instead of a list comprehension, and passing randomised names as variables instead of randomising in the Gib class itself. 认为我实际上只是创建一个实例,然后引用它十次,但我不知道为什么-我尝试使用for循环(而不是列表理解)来实现它,而是将随机名称作为变量传递Gib类本身的随机化。

import random
import string

class Evolver:
    def __init__(self, input_text, chance):
        self.input_text = list(input_text)
        self.gib_text = [random.choice(chars) for c in self.input_text]
        self.chance = chance
        self.popul = []

    def pop_gen(self):
        temp_popul = [Gib(self.gib_text, self.chance) for i in range(10)]
        self.popul = temp_popul

class Gib:
    def __init__(self, gib_text, chance):
        self.name = self.mutator(gib_text, chance)
        self.score = 0

    def mutator(self, gib_text, chance):
        for c in range(len(gib_text)):
            if chance >= random.randint(1, 100):
                gib_text[c] = random.choice(chars)
        return gib_text

chars = string.uppercase

e = Evolver("TEST", 100)
e.pop_gen()

for p in e.popul:
    print p, p.name

Any and all help appreciated! 任何和所有帮助表示赞赏!

You're creating 10 seperate instances with the same name . 您正在创建10个具有相同名称的单独实例。 Since Gib.name ends up being a list, when you mutate it in Gib.mutator , all references to that list see the change. 由于Gib.name最终是列表,因此当您在Gib.mutator对其进行突变时, Gib.mutator列表的所有引用都会看到更改。 When you create the Gib s in the first place, you pass them the same list ( self.gib_text ), so they all share the same list for a name and therefore they all end up with the same name (even if it gets mutated in Gib.mutator ). 首先创建Gib ,您将它们传递给相同的列表( self.gib_text ),因此它们都共享相同的name列表,因此它们都以相同的名称结尾(即使它在Gib.mutator )。 One workaround is to copy self.gib_text when you pass it to the initializer: 一种解决方法是在将self.gib_text传递给初始化self.gib_text时复制它:

def pop_gen(self):
    temp_popul = [Gib(self.gib_text[:], self.chance) for i in range(10)]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM