0

I have a class which contains a list. I would really like it if I could easily get the number of only the top level objects/classes I am adding to that list.

class Layer:
            class Neuron:
                netValue = 0.
                activationValue = 0.
                weights = []
                weightsAfterErrorSubtracted = []
                incomingError = 0.

                def __init__(self, numberOfWeights):
                    self.weights = random.random(int(numberOfWeights))

            neurons = [] 

            def __init__(self, numberOfNeurons, numberOfWeightsPerNeuron):
                for neuron in range(0, numberOfNeurons):
                self.neurons.append(self.Neuron(numberOfWeightsPerNeuron))

layer = Layer(40, 200)
print("The length of my list is: " + str(len(layer.neurons)))

The problem is, when I print out the length of the list after adding neurons, it includes all the weights in the neurons as well in that length, not just the number of neuron objects. Is there a way to easily just get the number of top level objects in a list, and not their children?

JakeJ
  • 2,361
  • 5
  • 23
  • 35
  • 1
    `Neuron.weights` is a class-level variable, not instance-level (as is `Layer.neurons`, for that matter). – Daniel Roseman Sep 07 '17 at 15:15
  • When I run your code (after fixing the indentation problem and the weird `random.random` call), I get "The length of my list is: 40". Is that not what you want? That's how many neurons are in the list, yes? – Kevin Sep 07 '17 at 15:15
  • Weird. In my version of python at least (I'll have to pull the version when I go home, but it's in the 2 range), it shows the total length to include the weights / subobjects. – JakeJ Sep 07 '17 at 15:59
  • Obviously the question is not a duplicate of the one posted, I really wish the mods / power users would read more carefully. In the given example, you have primitive type being added to a list. In my example, you have a class with a list in it, yes, but that class has subclasses that are added to the list in the constructor of the parent class. Further, the problems the other question had are not the same problems I am having and have nothing at all to do with each other. Please remove the marking as a duplicate. – JakeJ Sep 07 '17 at 16:10

0 Answers0