1

I am just starting with Python and have been stuck for the past hour with this: When traversing a linked list, the usual way would be to do something like this:

def traverse(self):
    current = self.head
    while current != None:
        print current.getData()
        current = current.getNext()

I don't understand why self.head doesn't change here, since we do current = self.head and current = current.getNext() later. Is self.head immutable?

4

1 回答 1

2

You are only ever assigning to a local name (variable); you are not assigning anything to the attributes of the objects involved.

In other words, only current is rebound to different objects, but current is a local name in the traverse() function. At no point do you assign to attributes on current or self.

This has otherwise nothing to do with mutability.

If you expected self.head to be affected by the line current = current.getNext() then you are perhaps misunderstanding what that line does. That line:

  • looks up the getNext attribute on the object referenced by current
  • calls the resulting object
  • stores the result of the call in a name current, rebinding it if it was bound before.

Rebinding simply discards the previous reference, so now current is pointing to whatever current.getNext() returned. The previous object that current was bound to is otherwise not changed. If there were no other references to that previous object anywhere else in Python, then that object is cleared from memory (deleted). In a linked list, presumably there is still a reference to it from the previous object in the list though.

You could see objects as balloons, and names (variables) as labels; assignment attaches the name to the object by a string. You can attach multiple labels to any given balloon, but a given label can only ever be attached to one balloon. Rebinding, then, simply cuts the string tying the label to the balloon, and retying it to another balloon. Any balloon that has no more strings attached to it simply flies away never to be seen again.

于 2013-08-25T22:35:54.987 回答