1

I'm having problems with the class variable "adjList" in my class "NodeCreate". It seems that whenever I append to adjList, it's extended for all the objects of that class, not just the one I'm calling. I think I'm fundamentally misunderstanding something, but I can't figure out what I should be doing instead. How can I append to each object's adjList?

code:

import sys class FileReader: edgeList = [] def __init__(self, args): with open(args, 'r') as inFile: #get the node list self.nodeList = inFile.readline().strip().split() while 1: line = inFile.readline().strip() if not line: break self.edgeList.append(line) class NodeCreate: adjList = [] def __init__(self, name): self.name = name def main(): nodeObjDict = {} #read in nodes fr = FileReader(sys.argv[1]) #make node objects for node in fr.nodeList: nodeObjDict[node] = NodeCreate(node) #make smaller items from edgeList for item in fr.edgeList: itemList = item.split() #add adjacent lists nodeObjDict[itemList[0]].adjList.append(itemList[1]) print(nodeObjDict[itemList[0]].adjList) if __name__ == "__main__": main() 

input:

A B C D E F G A B A D A F B C B G C D 

What I end up getting for my printed output is something like: ['B', 'D', 'F', 'C', 'G', 'D'] even for A.adjList. I was expecting just ['B', 'D', 'F'].

1 Answer 1

2

You are using a class variable when you want an instance variable. Basically a class variable is set for all objects of a class, and an instance variable is only set for one object.

Here is your class with adjList as an instance variable instead of a class variable:

class NodeCreate: def __init__(self, name): self.name = name self.adjList = [] 

Here's an answer I've written before that explains it in more detail: https://stackoverflow.com/a/12924803/1460235

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for the help. I was having a hard time understanding.
No problem; it's confusing at first.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.