0

好的,这是我的代码:

class foo():
    def x(self, arg = []):
        print arg
        if len(arg):
            print "arg already contains data"
        arg.append("one call were made")

很简单。我可以传递一个列表作为参数,但是,如果我不传递它,我会为我生成一个全新的列表,好吗?

但是看看当我调用该方法两次时会发生什么:

>>> ob = foo()
>>> ob.x()
[]
>>> ob.x()
['one call were made']
arg already contains data
>>> ob.x()
['one call were made', 'one call were made']
arg already contains data

这对我来说似乎违反直觉。我最初的想法是该列表将在函数调用时生成,然后在函数结束时与本地范围的其余部分一起销毁。

怎么了?为什么会这样?列表的状态存储在哪里?

4

0 回答 0