python类对象和变量生命周期

时间:2016-04-10 16:38:23

标签: python

class Node:
    def __init__(self):
        self.data = None # contains the data
        self.next = None # contains the reference to the next node


class linked_list:
    def __init__(self):
        self.cur_node = None
        self.counter = 0


    def add_node(self, data):
        new_node = Node() # create a new node
        new_node.data = data
        new_node.next = self.cur_node # link the new node to the' previous' node.
        self.cur_node = new_node #  set the current node to the new one.

    def list_print(self):
        node = self.cur_node # cant point to ll!
        while node:
            print node.data
            node = node.next




ll = linked_list()

ll.add_node(1)
ll.add_node(2)
ll.add_node(3)
ll.list_print()
  1. 我正在创建linked_list类的对象。
  2. 之后我调用了成员函数add_node()三次。

  3. 但是当我调用函数list_print时,它会打印3-> 2> 1.

  4. 我的问题是这是怎么打印的?据我说它应该打印" 3"只因为当我调用ll.list_print()时,self.cur_node的值等于3.所以如何打印所有三个输入。它在哪里存储以前的值" 2,1" ?请帮帮我。

1 个答案:

答案 0 :(得分:0)

在add_note方法中,您在声明最后一个之前将new_node.next =声明为self.cur_node,但是,这是不必要的。评论那条线!我添加了一个打印来检查该方法中的进度

class Node:
    def __init__(self):
        self.data = None # contains the data
        self.next = None # contains the reference to the next node


class linked_list:

    def __init__(self):
        self.cur_node = None
        self.counter = 0

    def add_node(self, data):
        new_node = Node() # create a new node
        new_node.data = data
        #new_node.next = self.cur_node # link the new node to the' previous' node.
        print(self.cur_node)
        self.cur_node = new_node #  set the current node to the new one.

    def list_print(self):
        node = self.cur_node # cant point to ll!
        while node:
            print node.data
            node = node.next

ll = linked_list()
ll.add_node(1)
ll.add_node(2)
ll.add_node(3)
ll.list_print()

enter image description here