0

On line 7&8 I am trying to set a group of object values according to an input array, but the property for all of the objects is set to 10 - the value in the last iteration of the loop. If somebody could explain why this isn't working how I would expect it to that would be amazing.

I am currently learning python, so I have no idea if there is an easier way to do this.

class Network:
    def __init__(self, input_data, layers, nodes, output_length):
        self.layer = [Layer(len(input_data))]
        self.layer += [Layer(nodes)] * layers
        self.layer += [Layer(output_length)]
        self.input = input_data
        for __i in range(len(self.input)):
            self.layer[0].nodes[__i].value = self.input[__i]

        for self.i in range(1, self.layer.__len__()):
            for self.j in range(0, self.layer[self.i].nodes.__len__()):
                self.layer[self.i].nodes[self.j].connection = [None] * self.layer[self.i - 1].nodes.__len__()

    def compute(self):
        for self.i in range(1, len(self.layer)):
            for self.j in range(0, len(self.layer[self.i].nodes)):
                for self.k in range(0, len(self.layer[self.i].nodes[self.j].connection)):
                    self.layer[self.i].nodes[self.k].value += self.layer[self.i-1].nodes[self.k] * self.layer[self.i].nodes[self.j].value[self.k]


class Layer:
    def __init__(self, nodes):
        self.nodes = [NodeObject()] * nodes


class NodeObject:
    def __init__(self):
        self.value = 0
        self.connection = [None]

    def set_value(self, value):
        self.value = value


i = Network([1,2,3,4,5,6,7,8,9,10], 2, 16, 10)
print(i.layer[0].nodes[2].value)

Thanks in advance,
Matt

Matt H
  • 1
  • 2
  • 2
    TL;DR: It's because `[Layer(nodes)] * layers` and similar lines create a bunch of references to the *same list*. List multiplication doesn't make copies. – Carcigenicate Jun 17 '18 at 15:03
  • @Carcigenicate It's definitely duplicate. It's one of the python problems everybody discover at some point. – Alex Yu Jun 17 '18 at 15:07
  • @Ingaz Ya, that and the mutable default argument "problem". Those are on the short-list of dupe targets I have memorized. – Carcigenicate Jun 17 '18 at 15:08
  • Also see https://stackoverflow.com/q/2612802/8033585 – AGN Gazer Jun 17 '18 at 15:09
  • Ah, I tried searching, but I was unsure what to look for. Thanks for the pointers. – Matt H Jun 17 '18 at 17:01
  • Congratulations! You solved one of "unpythonic problems" in python. Be prepared for "unexpected behaviour" of default function params and mind**k when you stumble on metaclasses – Alex Yu Jun 17 '18 at 21:19

0 Answers0