I am trying to build my own network of nodes and analyse it. I have a Node class and a Network class:
class Node():
def __init__(self, ID, team):
self.ID = ID
self.team = team
self.edge = (None, None)
class Network():
def __init__(self, number_of_green_nodes):
self.green_network = [Node(ID = i, team = "Green") for i in range(number_of_green_nodes)]
I then create a network object, network1, consisting of 10 Node objects:
network1 = network.Network(10)
I now want to iterate through the network’s list of nodes, and access some attributes of the Node objects. For instance, to access the ID attribute of each of the nodes, I do the following:
for i in network1.green_network:
print(network1.green_network[i].ID)
But this results in the following error:
TypeError: list indices must be integers or slices, not Node
So how is this done?
>Solution :
network1.green_network is a list and with the for cycle you’re directly iterating through that list:
for node in network.green_network:
print(node.ID)
Or, if you need the index, that is useless since it is the same as the ID for how you initialize the network:
for i, node in enumerate(network.green_network):
print(f'Node in position {i} has ID {node.ID}')