Ci3
Ci3

Reputation: 4842

Class variable not static?

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'].

Upvotes: 1

Views: 64

Answers (1)

Matthew Adams
Matthew Adams

Reputation: 10126

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

Upvotes: 2

Related Questions