Results 1 to 4 of 4

Thread: Python list of classes issue

  1. #1
    Join Date
    Jan 2009
    Beans
    33

    Python list of classes issue

    Hi guys,

    I'm running into trouble with some Python stuff. I have a list that has seven copies of a class and I am intending to change just the values of one of them but whenever I do it changes the value for all.

    Here is the class:

    Code:
    class Node:
        previous = -1
        distFromSrc = 1000000
        visited = False
    And here is how I create the list:

    Code:
    def createNodeTable(network):
        nodeTable = []
        for line in network:
            nodeTable.append(Node)
        return nodeTable
    'network' is a list of length 7 so when I print the 'nodeTable[x].visited' before I attempt to make any changes to the values I get 'False' for every one.

    If I call the following function however all of the '.visited' values change to false not just the one I am intending to change.

    Whatever 'currentNode' is changed to I get the same issue:

    Code:
    def setVisited(currentNode, nodeTable):
        nodeTable[currentNode].visited = True
        return nodeTable
    Is there an issue with the setVisited function or is it to with the nodeTable? I don't even know where to start to try to fix this.

  2. #2
    Join Date
    May 2007
    Location
    Leeds, UK
    Beans
    1,675
    Distro
    Ubuntu

    Post Re: Python list of classes issue

    I'm no Python expert, but doesn't an instance variable need to be prefixed with self?

    Code:
    class Node:
        def __init__(self):
            self.previous = -1
            self.distFromSrc = 1000000
            self.visited = False
    Otherwise they will be class variables.

  3. #3
    Join Date
    Jan 2009
    Beans
    33

    Re: Python list of classes issue

    That's one way of fixing it. The way I found after however was just to change the append line to Node() so each is a new instance.

  4. #4
    Join Date
    May 2008
    Location
    UK
    Beans
    1,451
    Distro
    Ubuntu 8.04 Hardy Heron

    Re: Python list of classes issue

    you have to do both I think.

    Your original code creates a new instance once, and appends it to the list 7 times, and creates within the class a set of Class variables - i.e. every instance of the class you create will share the same data.
    Tony - Happy to try to help.
    Unless otherwise stated - all code posted by me is untested. Remember to Mark the Thread as Solved.
    Ubuntu user number # 24044 Projects : TimeWarp - on the fly Backups

Tags for this Thread

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •