简体   繁体   中英

Python: How to sum up all elements from a list in the CLASS

class Neuron:
    def __init__(self, inbound_neurons=[], label=''):
        self.label = label
        self.inbound_neurons = inbound_neurons
        self.outbound_neurons = []
        self.value = None

        for n in self.inbound_neurons:
            n.outbound_neurons.append(self)

    def forward(self):
        raise NotImplemented

class Input(Neuron):
    def __init__(self):
        Neuron.__init__(self)

    def forward(self, value=None):
        if value is not None:
            self.value = value

class Add(Neuron):
    def __init__(self, *inputs):
        Neuron.__init__(self, inputs)

    def forward(self):
        for n in self.inputs:
            self.value = self.value + n

Add() is the subclass of class Neuron, I have met some difficulties to use loop to add all the elements of the inputs array.

class Add(Neuron):

    def __init__(self, *inputs):
        Neuron.__init__(self, inputs)

    def forward(self):
        self.value = 0
        for n in self.inbound_neurons:
            self.value = self.value + n.value

        return(self.value)

The function 'forward' in Class Add has a loop to sum all elements of inbound_neurons.

Firt off this line of code should be:

for n in self.inbound_neurons:
        self.outbound_neurons.append(self)

self.inputs was never defined in your Class. In order to loop through the inputs, you'd have to have:

    def __init__(self, *inputs):
        self.inputs = inputs
        Neuron.__init__(self, inputs)

However, it looks like inputs would be a list with two items, another list and maybe a string in it. These will not concate together. It looks like instead you want to sum the total of self.inbound_neurons .

It's not related to your question, but VERY important: you should NOT use mutable data types (as list) for function/method defaults.

Your code should be updated like this:

class Neuron:
    def __init__(self, inbound_neurons=None, label=''):
        self.inbound_neurons = inbound_neurons or []
        # ...

Why you should do this way is explained here: "Least Astonishment" and the Mutable Default Argument

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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