意外的list.append行为

时间:2016-10-12 13:32:30

标签: python list

我正在处理堆栈并偶然发现以下问题: 代码是:

class stack_element(object):
    element = None

    @classmethod
    def __init__(self, value):
        print "Created element {0}".format(value)
        self.element = value

    @classmethod
    def get(self):
        return self.element

    def print_element(self):
        print self.element

class stack (object):
    stack_list = []

    @classmethod
    def push (self, value):
        self.stack_list.append(stack_element(value))

    def pop(self):
        if len(self.stack_list) > 0:
            element = self.stack_list.pop()
            return element.get()
        else:
            return None

    def print_stack(self):
        print "-------------> Stack length is {0}".format(len(self.stack_list))
        print "Elements are:"
        for i in self.stack_list:
            print "Element is {0}, element content is {1}".format(i, i.get())
        print "End of stack"

    def __iter__(self):
        return self

    def next(self):
        return self


def execute():
    mystack = stack()
    mystack.print_stack()
    mystack.push("Anna")
    mystack.print_stack()
    mystack.push("Nina")
    mystack.print_stack()

    while mystack.pop() != None:
        mystack.print_stack()

if __name__ == "__main__":
    execute()

输出奇怪的是:

-------------> Stack length is 0
Elements are:
End of stack
Created element Anna
-------------> Stack length is 1
Elements are: Element is <__main__.stack_element object at 0x7f3067a24690>, Element content is Anna
End of stack
Created element Nina
-------------> Stack length is 2
Elements are:
Element is <__main__.stack_element object at 0x7f3067a24690>, element content is Nina
Element is <__main__.stack_element object at 0x7f3067a24710>, element content is Nina
End of stack
-------------> Stack length is 1
Elements are:
Element is <__main__.stack_element object at 0x7f3067a24690>, element content is Nina
End of stack
-------------> Stack length is 0
Elements are:
End of stack

正如您在第二步中看到的,堆栈对象地址没有改变,但是对象内容被改变了。我这里没有特别喜欢做什么。有人可以解释一下吗?

0 个答案:

没有答案